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'})

Python 中 ValueError: I/O operation on closed file 错误

要解决这个错误,请确保正确缩进代码并将其移至 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')

任何试图访问该文件的代码都需要正确缩进。

或者,我们可以将文件对象存储到变量中并手动关闭它。

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

我们可以使用文件对象的 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() 语句时缩进尝试正确访问文件的代码。