在Python中读取目录的安全方法

Ron*_*gan 5 python directory system-calls

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)))
Run Code Online (Sandbox Code Playgroud)

这工作正常,我已经测试过,当目录不存在时它不会窒息而死,但我正在读一本Python书,我应该在打开文件时使用"with".有没有一种首选方式来做我正在做的事情?

IT *_*nja 4

你很好。该os.listdir功能不会打开文件,所以最终你没问题。with您可以在读取文本文件或类似文件时使用该语句。

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()).
Run Code Online (Sandbox Code Playgroud)