Linux 拨号vps windows公众号手机端

怎么在python中关闭已打开的文件

lewis 6年前 (2019-03-27) 阅读数 8 #程序编程
文章标签 python

在python中关闭文件方法有:1.使用close()函数关闭;2.使用with语句关闭;3.使用try-finally块关闭;

在python中关闭文件方法有以下几种

1.使用close()函数关闭

# 打开文件

fo = open("runoob.txt", "wb")

print "文件名为: ", fo.name

# 关闭文件

fo.close()

2.使用with语句关闭

with open('dog_breeds.txt') as reader:

3.使用try-finally块关闭

reader = open('dog_breeds.txt')

try:

finally:

reader.close()

版权声明

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

发表评论:

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

热门