Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe way to read directory in Python

try:
    directoryListing = os.listdir(inputDirectory)
    #other code goes here, it iterates through the list of files in the directory

except WindowsError as winErr:
    print("Directory error: " + str((winErr)))

This works fine, and I have tested that it doesnt choke and die when the directory doesn't exist, but I was reading in a Python book that I should be using "with" when opening files. Is there a preferred way to do what I am doing?

like image 215
Ronald Dregan Avatar asked Jul 14 '12 03:07

Ronald Dregan


1 Answers

You are perfectly fine. The os.listdir function does not open files, so ultimately you are alright. You would use the with statement when reading a text file or similar.

an example of a with statement:

with open('yourtextfile.txt') as file: #this is like file=open('yourtextfile.txt')
    lines=file.readlines()                   #read all the lines in the file
                                       #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()).
like image 81
IT Ninja Avatar answered Oct 16 '22 03:10

IT Ninja