如何在Python中关闭打开的文件?

要在python中关闭打开的文件,只需在文件对象上调用close函数。

例如

>>> f = open('hello.txt', 'r')
>>> # Do stuff with file
>>> f.close()

尽管这样做不安全,但请尽量不要以这种方式打开文件。使用...打开代替。

例如

with open('hello.txt', 'r') as f:
    print(f.read())

退出with块后,文件自动关闭。