是我还是在 python 中打开或关闭文件使用不同的方法使其真的不直观? 有更好的方法吗?
例子:
f = open('file.txt', 'r')
try:
# do stuff with f
finally:
f.close()
现在,为什么我使用内置的“函数”打开但关闭文件我没有函数“关闭”但我必须调用“对象”方法“关闭”。
请您参考如下方法:
使用 with关键字,使其更直观。当您缩进时,它会自动关闭文件。来自文档:
The ‘with‘ statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed.
...
After this statement has executed, the file object in f will have been automatically closed, even if the for loop raised an exception part- way through the block.
一个例子:
with open('file.txt', 'r') as f:
# do stuff with f
# Do some other stuff - we dropped down a level of indentation, so the file is closed
更具体地说,它最初会调用上下文的 __enter__方法 - 这是初始文件打开。 __enter__ 返回的任何内容都使用 as 语句设置 - 在这种情况下,文件返回 self 并将其设置为 f。当 with block 完成时,它将调用上下文的 __exit__。方法。对于文件上下文,这会执行正常的 finally block 关闭文件处理。
请注意,with block 不会为您处理异常,它只是确保 __exit__ 被调用(这将优雅地关闭文件),即使它们确实发生了.因此,如果您在处理文件时遇到 ValueError,您仍然需要 try...catch block inside block 来处理可能对您的计算/脚本/等造成的任何影响。
正如 Marcin 所指出的,大多数语言在 try...catch...finally block 中执行此操作。例如,Java 会这样做:
BufferedReader reader = null;
try {
reader = new BufferedReader(new File("file.txt"));
// Read in data and do stuff
} catch (Exception e) {
// Shouldn't be this generic, but you get the idea
e.printStackTrace();
} finally {
// Always executes
if (reader != null) reader.close();
}
