在 python 中写入文本文件时出错 [I/O 对已关闭文件的操作]
error when writing to a text file in python [I/O operation on closed file]
我想在 python 中创建一个文件,但我遇到了一个错误。我不知道为什么会出现这个问题,我确实在网上看过但找不到解决我问题的方法。我已经随机导入了,我确实有一个 enc1
的列表
f = open("Skins.txt",'w')
for r in range(1,1201):
f.write(str(r))
f.write(",")
f.write(random.choice(enc1))
f.write("\n")
f.close()
错误:
f.write(str(r))
ValueError: I/O operation on closed file.
您试图在每次迭代结束时关闭文件。将关闭操作移出循环块。
f = open("Skins.txt",'w')
for r in range(1,1201):
f.write(str(r))
f.write(",")
f.write(random.choice(enc1))
f.write("\n")
f.close()
或者使用 with
在循环外打开文件并使用 writelines
写入数据:
with open("Skins.txt",'w') as f:
f.writelines("{},{}\n".format(r, random.choice(enc1)) for r in range(1,1201))
您正在循环内关闭文件,因此在第一次迭代后文件被关闭,因此尝试写入它失败并出现您收到的错误。
我建议使用 with
statement to open the file (so that it automatically handles closing the file for you), so that this kind of issues does not occur. Also, you do not need all those different f.write()
statements, you cna use str.format()
并在单个 .write()
中执行相同的操作。
例子-
with open("Skins.txt",'w') as f:
for r in range(1,1201):
f.write("{},{}\n".format(r, random.choice(enc1)))
我想在 python 中创建一个文件,但我遇到了一个错误。我不知道为什么会出现这个问题,我确实在网上看过但找不到解决我问题的方法。我已经随机导入了,我确实有一个 enc1
的列表f = open("Skins.txt",'w')
for r in range(1,1201):
f.write(str(r))
f.write(",")
f.write(random.choice(enc1))
f.write("\n")
f.close()
错误:
f.write(str(r))
ValueError: I/O operation on closed file.
您试图在每次迭代结束时关闭文件。将关闭操作移出循环块。
f = open("Skins.txt",'w')
for r in range(1,1201):
f.write(str(r))
f.write(",")
f.write(random.choice(enc1))
f.write("\n")
f.close()
或者使用 with
在循环外打开文件并使用 writelines
写入数据:
with open("Skins.txt",'w') as f:
f.writelines("{},{}\n".format(r, random.choice(enc1)) for r in range(1,1201))
您正在循环内关闭文件,因此在第一次迭代后文件被关闭,因此尝试写入它失败并出现您收到的错误。
我建议使用 with
statement to open the file (so that it automatically handles closing the file for you), so that this kind of issues does not occur. Also, you do not need all those different f.write()
statements, you cna use str.format()
并在单个 .write()
中执行相同的操作。
例子-
with open("Skins.txt",'w') as f:
for r in range(1,1201):
f.write("{},{}\n".format(r, random.choice(enc1)))