A safe way to read a 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 tested that it does not choke or die when the directory does not exist, but I read in a Python book that I should use the “c” when opening files. Is there a preferred way to do what I do?

+5
source share
2 answers

You are doing great. The function os.listdirdoes not open files, so in the end you are fine. You must use the instruction withwhen reading a text file or similar file.

operator example with:

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()).
+4
source

What you do is beautiful. With a really preferred way to open files, but listdir is perfectly acceptable for simply reading a directory.

+2
source

All Articles