执行此python代码时,我看到以下错误。这是什么问题? 我用过" sys.stdout.close()"我仍然看到这些错误。
#! /usr/bin/python
import sys
a = [ 10, 12, 13, 14]
sys.stdout=open("file.txt","w")
print("++++++++")
print("***xyz***")
print("++++++++")
sys.stdout.close()
for i in a:
print i
Traceback (most recent call last):
File "./test3.py", line 10, in <module>
print i
ValueError: I/O operation on closed file`
答案 0 :(得分:1)
您正在尝试在关闭它之后写入stdout(您的文件)。在第8行关闭文件,在第10行,您调用print
。
如果要将列表a
写入文件,则应在for
循环后将其关闭。
答案 1 :(得分:0)
考虑使用with open
,因为您不必担心关闭它。如果您的列表需要是一个列表,那么考虑将其腌制而不是将其写入文件。 Pickling将您的数据序列化。
#!python3
# import module
from os import system
import pickle
# clear the screan
system('cls')
a = [ 10, 12, 13, 14]
# write a list to file, but it has to be written as a string
with open('file.txt', 'w') as wf:
wf.write(str(a))
# when you open your file up, the data is a string
with open('file.txt', 'r') as fp:
for item in fp:
print(item)
print(type(item))
# if you want to retain your data as a list, then pickle it
output = open('file.pkl', 'wb')
pickle.dump(a, output)
output.close()
# open up a pickled file
pkl_file = open('file.pkl', 'rb')
data = pickle.load(pkl_file)
print(data)
print(type(data))
pkl_file.close()