在关闭的文件上附加Python 3 I/O操作中的文件

在关闭的文件上附加Python 3 I/O操作中的文件,python,python-3.x,Python,Python 3.x,我能够在代码开始时打开csv文件并将一些标题写入其中: ## Create the output file with open(output_file, mode='w+') as csv_file: fieldnames = ['Name', 'Instance ID', 'Type', 'State', 'Private IP', 'Public IP', 'Region', 'Availability Zone', 'Launch Time' ]

我能够在代码开始时打开csv文件并将一些标题写入其中:

## Create the output file
with open(output_file, mode='w+') as csv_file:
                    fieldnames = ['Name', 'Instance ID', 'Type', 'State', 'Private IP', 'Public IP', 'Region', 'Availability Zone', 'Launch Time' ]
                    writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
                    writer.writeheader()
但在同一个程序中,我构建了一个EC2实例列表,并尝试在代码的后面将该列表打印到同一个文件中,我得到了以下错误:

File "C:\Users\tdunphy\AppData\Local\Programs\Python\Python37-32\lib\csv.py", line 155, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
ValueError: I/O operation on closed file.
这是我试图附加到文件的代码,它会产生上述错误:

with open(output_file, mode='a+') as csv_file:
    writer.writerow({'Name': name, 'Instance ID': instance_id, 'Type': instance_type, 'State': instance_state, 'Private IP': private_ips, 'Public IP': public_ips, 'Region': aws_region, 'Availability Zone': availability_zone, 'Launch Time': launch_time_friendly})

为什么我不能写入这个文件?如何更正此问题?

您可能需要在尝试编写Row之前添加回这一行,因为旧的编写器可能仍然引用内存中的“已关闭”文件:

writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
如果与相同

try:
    f1 = open(path, 'w+') as f:
    s = store(f1)
finally:
    f1.close()
try:
    f2 = open(path, 'a+')
    s.operate_on()
finally:
    f2.close()
也许这更能说明你的问题所在。您正在存储一个打开的文件对象,然后将其关闭,然后打开一些从未使用过的其他文件对象
f2
,并尝试对关闭的文件进行操作

您的解决方案是使用块将
writer.writerow(…)
放在第一个
中,或者直接执行

csv_file = open(output_file, mode='w+')
以后要小心关上它

或者,使用新文件对象创建一个新的
csv.DictWriter

csv_file = open(output_file, mode='w+')