新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

Python中如何关闭文件句柄,python 关闭

发布时间:2024-03-30 17:03:55

Python中如何关闭文件句柄

在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