如何在Python中安全地打开/关闭文件?

open()打开一个文件。您可以像这样使用它:

f = open('my_file', 'r+')
my_file_data = f.read()
f.close()

上面的代码在读取模式下打开“ my_file”,然后将从my_file读取的数据存储在my_file_data中并关闭文件。open的第一个参数是文件的名称,第二个参数是打开模式。它确定如何打开文件。

例如

– If you want to read the file, pass in r
– If you want to read and write the file, pass in r+
– If you want to overwrite the file, pass in w
– If you want to append to the file, pass in a

当您打开文件时,操作系统会提供一个文件句柄来读取/写入文件。使用完文件后,需要关闭它。如果您的程序遇到错误并且没有调用f.close(),则您没有释放文件。为了确保它不会发生,您可以将open(...)用作f语法,因为它会自动关闭文件,而不管是否遇到错误:

with open('my_file', 'r+') as f:
    my_file_data = f.read()