[英]I'm trying to export a Python list to a .txt file, but the text file ends up having too few lines
I have a list (List) of 4196 elements, all equal to either -1 or 1. I want to export the list to a .txt file. 我有一个包含4196个元素的列表(列表),所有元素都等于-1或1。我想将列表导出到.txt文件。 Here's the code I used:
这是我使用的代码:
file = open('file.txt','w')
for item in List:
print>>file, item
For some reason, the .txt file only has 2870 elements. 由于某种原因,.txt文件仅包含2870个元素。 (The same thing happened when I tried another way of exporting the list, but I know there are 4196 elements!)
(当我尝试另一种导出列表的方法时,发生了同样的事情,但是我知道有4196个元素!)
Thanks for any help, 谢谢你的帮助,
Zach 扎克
You need to close the file. 您需要关闭文件。 You can't easily tell from the number of lines, but I'd expect the size of the file to be 4096 or 8192, which hints that only a whole number of blocks have been flushed.
您无法从行数中轻易看出,但我希望文件的大小为4096或8192,这暗示仅刷新了全部块。 After you call
file.close()
, the rest of the data should be written. 调用
file.close()
,应写入其余数据。
You can use a with
statement to close the file automatically : 您可以使用
with
语句自动关闭文件 :
with open('file.txt','w') as file:
for item in List:
print>>file, item
Something like this? 像这样吗
List = open("file.txt").read()
new = []
ff = open("new_file.txt", 'w')
for i in List:
new.append(i)
ff.write(str(new))
ff.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.