温馨提示×

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

养鱼的猫咪
536
2021-04-22 11:57:45
栏目: 编程语言

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

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

在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()

0