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

时间:2012-07-14 03:38:53

标签: 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)))

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

2 个答案:

答案 0 :(得分: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()).

答案 1 :(得分:2)

你做得很好。确实是打开文件的首选方式,但listdir只是读取目录是完全可以接受的。