Python 中 ValueError: I/O operation on closed file 错误
Python“ValueError: I/O operation on closed file”发生在我们试图对一个关闭的文件执行操作时。 要解决该错误,需要确保在使用 with open()
语句时缩进尝试正确访问文件的代码。
看下面的代码
import csv
with open('employees.csv', 'w', newline='', encoding='utf-8') as csvfile:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
print(csvfile.closed) # 👉️ False
# 👇️ forgot to indent code 👇️
# ⛔️ ValueError: I/O operation on closed file.
print(csvfile.closed) # 👉️ True
writer.writeheader()
writer.writerow({'first_name': 'Alice', 'last_name': 'Smith'})
我们忘记缩进写入文件的代码,所以
with open()
语句自动关闭了文件,我们对关闭的文件执行了 I/O 操作。
要解决这个错误,请确保正确缩进代码并将其移至 with
语句中,不要混用制表符和空格。
import csv
with open('employees.csv', 'w', newline='', encoding='utf-8') as csvfile:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
# ✅ code is now indented correctly
writer.writeheader()
writer.writerow({'first_name': 'Alice', 'last_name': 'Smith'})
writer.writerow({'first_name': 'Bob', 'last_name': 'Smith'})
with open()
语法负责自动关闭文件,即使抛出异常也是如此。
这是另一个例子。
file_name = 'example.txt'
with open(file_name, 'w', encoding='utf-8') as my_file:
# ✅ code is indented correctly
my_file.write('first line' + '\n')
my_file.write('second line' + '\n')
my_file.write('third line' + '\n')
确保在
with open()
语句之后没有尝试访问文件的代码。
任何试图访问该文件的代码都需要正确缩进。
或者,我们可以将文件对象存储到变量中并手动关闭它。
file_name = 'example.txt'
my_file = open(file_name, 'w', encoding='utf-8')
my_file.write('first line' + '\n')
my_file.write('second line' + '\n')
my_file.write('third line' + '\n')
my_file.close() # 👈️ manually close file
请注意
,最好使用with open()
语法,因为它会在我们完成后自动关闭文件。
我们可以使用文件对象的 closed 属性来检查它是否已关闭。
file_name = 'example.txt'
with open(file_name, 'w', encoding='utf-8') as my_file:
# ✅ code is correctly indented
my_file.write('first line' + '\n')
my_file.write('second line' + '\n')
my_file.write('third line' + '\n')
print(my_file.closed) # 👉️ False
print(my_file.closed) # 👉️ True
最后一行代码没有缩进,所以此时文件已经关闭。
总结
Python“ValueError: I/O operation on closed file”发生在我们试图对一个关闭的文件执行操作时。 要解决该错误,需要确保在使用 with open()
语句时缩进尝试正确访问文件的代码。
相关文章
Python pandas.pivot_table() 函数
发布时间:2024/04/24 浏览次数:82 分类:Python
-
Python Pandas pivot_table()函数通过对数据进行汇总,避免了数据的重复。
在 Python 中将 Pandas 系列的日期时间转换为字符串
发布时间:2024/04/24 浏览次数:894 分类:Python
-
了解如何在 Python 中将 Pandas 系列日期时间转换为字符串
在 Python Pandas 中使用 str.split 将字符串拆分为两个列表列
发布时间:2024/04/24 浏览次数:1124 分类:Python
-
本教程介绍如何使用 pandas str.split() 函数将字符串拆分为两个列表列。
在 Pandas 中将 Timedelta 转换为 Int
发布时间:2024/04/23 浏览次数:231 分类:Python
-
可以使用 Pandas 中的 dt 属性将 timedelta 转换为整数。
Python 中的 Pandas 插入方法
发布时间:2024/04/23 浏览次数:112 分类:Python
-
本教程介绍了如何在 Pandas DataFrame 中使用 insert 方法在 DataFrame 中插入一列。
使用 Python 将 Pandas DataFrame 保存为 HTML
发布时间:2024/04/21 浏览次数:106 分类:Python
-
本教程演示如何将 Pandas DataFrame 转换为 Python 中的 HTML 表格。
如何将 Python 字典转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:73 分类:Python
-
本教程演示如何将 python 字典转换为 Pandas DataFrame,例如使用 Pandas DataFrame 构造函数或 from_dict 方法。
如何在 Pandas 中将 DataFrame 列转换为日期时间
发布时间:2024/04/20 浏览次数:101 分类:Python
-
本文介绍如何将 Pandas DataFrame 列转换为 Python 日期时间。