Linux 拨号vps windows公众号手机端

Python中怎么关闭文件句柄

lewis 7年前 (2018-03-19) 阅读数 11 #程序编程
文章标签 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
版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门