Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Aug 5th, 2012  |  syntax: None  |  size: 0.59 KB  |  hits: 9  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Safe way to read directory in Python
  2. try:
  3.     directoryListing = os.listdir(inputDirectory)
  4.     #other code goes here, it iterates through the list of files in the directory
  5.  
  6. except WindowsError as winErr:
  7.     print("Directory error: " + str((winErr)))
  8.        
  9. with open('yourtextfile.txt') as file: #this is like file=open('yourtextfile.txt')
  10.     lines=file.readlines()                   #read all the lines in the file
  11.                                        #when the code executed in the with statement is done, the file is automatically closed, which is why most people use this (no need for .close()).