在Python中,關閉文件句柄可以使用close()
方法來實現。只需要在文件句柄后面加上.close()
即可關閉文件句柄,如下所示:
file = open("file.txt", "r")
# do something with the file
file.close()
另外,還可以使用with
語句來打開文件,這樣可以在結束時自動關閉文件句柄,無需手動調用close()
方法,示例如下:
with open("file.txt", "r") as file:
# do something with the file
pass
# file is automatically closed after exiting the with block