【发布时间】:2015-08-18 13:13:31
【问题描述】:
我有以下代码:
import glob, os
for file in glob.glob("\\*.txt"):
if os.access(file, os.R_OK):
# Do something
else:
if not os.access(file, os.R_OK):
print(file, "is not readable")
else:
print("Something went wrong with file/dir", file)
break
但我不完全确定这是否是正确的做法。错误使用try 和catch 会更好吗?如果是这样,我该如何尝试以提高可读性?请注意我的 else 语句中的 break。一旦无法读取文件,我就想中止循环。
【问题讨论】:
-
您可以尝试打开文件以读取并捕获产生的异常(如果有)。这也将比您当前的方法更强大,因为在两次调用
os.access()之间文件可能变得不可读(甚至消失)。 -
您实际上是在阅读
# Do something部分中的文件还是只是想测试它的可读性? -
@PM2Ring 我实际上正在那里读取文件。
标签: python if-statement try-catch