简体   繁体   English

我正在尝试将Python列表导出到.txt文件,但文本文件最终的行数太少

[英]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.

相关问题 我正在尝试将随机数写入文件,然后从 Python 中的行创建一个列表,但列表也需要 '\\n' - I'm trying to write random numbers to a file and then make a list from lines in Python but list takes '\n' too 我试图让机器人从 700 行的实际 txt 文件中发送 10 行文本 - I'm trying to make a bot send 10 lines of text from an actual txt file of 700 lines 我正在尝试将文本文件转换为字典或列表Python - I'm trying to convert a text file to dictionary or a list Python 我在尝试使用CSV文件和列格式将数字(0-10)读入Python 3的列表时遇到麻烦。 - I'm having trouble trying to read the numbers (0 - 10) into a list in Python 3 using CSV file and in a column format. 将 arrays 列表导出到 python 中的 txt 文件 - export list of arrays to txt file in python 用python在新行上将文本写入txt文件? - Writing text to txt file in python on new lines? 我正在尝试将前三名高分保存到单独行的txt文件中 - I'm trying to save the top three highscores to a txt file on seperate lines 尝试从文本文件中提取行并将其放入python 3中的列表中 - Trying to pull lines from a text file puting it into a list in python 3 我是一个完整的初学者。 如何在 R 或 Python 中将 txt 文件(电影脚本)转换为表格(字符和行)? - I'm a complete beginner! How to I convert a .txt file (film script) to a table (characters and lines) in R or Python? 我正在尝试使用for循环打印.txt文件的多行。 总是缺少最后三行 - I'm trying to print a number of lines of a .txt file using a for loop. It's always missing the last three lines
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM