在Python中,关闭一个文件通常有以下几种方法:
1. 使用 `close()` 方法:
file = open('file_path', 'r') 打开文件
文件操作
file.close() 关闭文件
2. 使用 `with` 语句:
with open('file_path', 'r') as file:
文件操作
文件会在with语句块结束后自动关闭
3. 使用 `try-finally` 块:
file = open('file_path', 'r') 打开文件
try:
文件操作
finally:
file.close() 关闭文件
4. 使用 `with open` 语句,无需显式调用 `close()` 方法:
with open('file_path', 'r') as file:
文件操作
文件会在with语句块结束后自动关闭