当出现 FileNotFoundError 异常时,我是否应该使用 file.close() 关闭文件?
Should I close a file with file.close() when there is a FileNotFoundError exception?
我正在尝试打开 python 中的文件并在文件不存在时打印一条消息。但是我很纠结异常发生时要不要关闭文件
try:
file = open(sys.argv[1], "r")
file.close() # should I do this?
except OSError:
print(f"{sys.argv[1]} file not found.")
检查文件是否存在的更简单方法:
import os
if not os.path.exists(sys.argv[1]):
print(f"{sys.argv[1]} file not found.")
但要回答您的问题,```file.close()`` 只有在文件存在并且您成功打开文件时才会发生。不是在异常发生的时候。
编辑:
正如@ekhumoro 所指出的,上面有一个竞争条件(当其他进程访问该文件时)。如果没有其他进程访问该文件,则上述代码有效。
@ekhumoro 指出的解决方案是使用您原来的 try/except 方法。
我正在尝试打开 python 中的文件并在文件不存在时打印一条消息。但是我很纠结异常发生时要不要关闭文件
try:
file = open(sys.argv[1], "r")
file.close() # should I do this?
except OSError:
print(f"{sys.argv[1]} file not found.")
检查文件是否存在的更简单方法:
import os
if not os.path.exists(sys.argv[1]):
print(f"{sys.argv[1]} file not found.")
但要回答您的问题,```file.close()`` 只有在文件存在并且您成功打开文件时才会发生。不是在异常发生的时候。
编辑: 正如@ekhumoro 所指出的,上面有一个竞争条件(当其他进程访问该文件时)。如果没有其他进程访问该文件,则上述代码有效。
@ekhumoro 指出的解决方案是使用您原来的 try/except 方法。