Python中安全读取目录的方法

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”语句。那么有没有更好的方法来实现我正在做的事情呢?

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()).

1
好的!谢谢。我是Python的新手,正在努力学习正确的做事方式,而不是“让它工作”。 - Ronald Dregan
没问题,我会添加一个with语句的示例供参考。 - IT Ninja
如果您想提供更多的知識,那麼“with”是做什麼的呢?它只是嘗試打開/讀取文件時可能出現的一系列錯誤,並將其捆綁成一個錯誤嗎?例如損壞、不存在等。 - Ronald Dregan
1
@RonaldDregan -- 它基本上确保在退出块时刷新和关闭文件。这样,您就不会意外地保留占用文件系统资源的引用。 - mgilson

2
你正在做的很好。使用with确实是打开文件的首选方式,但listdir仅用于读取目录也是完全可接受的。

没问题。希望你在使用Python时玩得愉快。 - Wulfram
是的,到目前为止我非常喜欢它。我迄今为止主要做的是C++和Java。 - Ronald Dregan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接