Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中读取目录的安全方法_Python_Directory_System Calls - Fatal编程技术网

Python中读取目录的安全方法

Python中读取目录的安全方法,python,directory,system-calls,Python,Directory,System Calls,这很好,我已经测试过,当目录不存在时,它不会阻塞和死亡,但我在一本Python书中读到,打开文件时应该使用“with”。有没有更好的方法来做我正在做的事情?你正在做的很好。With确实是打开文件的首选方式,但是listdir完全可以用于读取目录。您完全可以。os.listdir函数不会打开文件,因此最终您不会有问题。阅读文本文件或类似文件时,可以使用with语句 with语句的一个示例: try: directoryListing = os.listdir(inputDirectory)

这很好,我已经测试过,当目录不存在时,它不会阻塞和死亡,但我在一本Python书中读到,打开文件时应该使用“with”。有没有更好的方法来做我正在做的事情?

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

您完全可以。
os.listdir
函数不会打开文件,因此最终您不会有问题。阅读文本文件或类似文件时,可以使用
with
语句

with语句的一个示例:

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语句示例仅供参考。如果您想提供更多知识,“with”做什么。它是否只是尝试了一些在打开/读取文件时可能出错的事情,并将其捆绑成一个错误?腐败,不在那里,,etc@RonaldDregan--它基本上确保在退出块时刷新并关闭文件。这样,您就不会意外地保留占用文件系统资源的引用。感谢您的反馈!没问题。我希望你喜欢你和蟒蛇的冒险,到目前为止我非常喜欢。到目前为止,我已经做了大部分C++和java。
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()).