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

标签 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”。是否有首选方法来完成我正在做的事情?

最佳答案

你很好。 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/

相关文章:

python - 使用 pd.isin() 检查一列中的值是否在另一列的列表中

c - gettimeofday 和clock_gettime 哪个更快?

python - 为什么包络曲线一开始就是错误的?

python - 使用matplotlib subplot排列饼图

python - 如何将一列从另一个数据帧连接到特定列?

windows-vista - Vista 和 ProgramData

c# - LINQ 链接中的 Any() 运算符

java - java读取目录的方法

c - 我应该在 C 中声明系统调用函数吗?

c - C编译器如何决定是调用库函数还是系统调用