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)))
这工作正常,我已经测试过当目录不存在时它不会阻塞和死机,但我在一本 Python 书中读到我应该在打开文件时使用“with”。是否有首选方法来完成我正在做的事情?
最佳答案
你很好。 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()).
关于python - 在 Python 中读取目录的安全方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11480812/