5
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”。有没有首选的方法来做我正在做的事情?

4

2 回答 2

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()).
于 2012-07-14T03:43:44.743 回答
2

你在做什么很好。With 确实是打开文件的首选方式,但 listdir 仅用于读取目录是完全可以接受的。

于 2012-07-14T03:41:58.553 回答