繁体   English   中英

使用 file.write python 写入文件的额外行

[英]Extra lines written to file using file.write python

我有一个长度为 34199 的列表“test_words”,我希望将此列表的每个元素写入文件“test_vocab.txt”

这是我实现相同目标的代码:

test_file = open('test_vocab.txt','w')

print(len(test_words))

count = 0

for item in test_words:
    print(count)
    test_file.write("%s\n" % item)
    count=count+1
test_file.close()

现在的问题是,即使列表只包含 34199 个元素,即使我在循环的每次迭代中打印出 'count',它也只能达到 34199,实际文件包含 35545 行。

这似乎很奇怪。 循环仅运行 34199 次,但文件如何包含 35545 行? 我什至在使用“test_file.close()”写入后立即关闭了文件。

我的文件应该只包含 34199 行。 有人可以帮我解决这个问题吗? 我不知道如何进一步

尝试以下操作:

for x in (test_words):
    test_file.write(x)

你得到额外行的原因来自你放置的换行符。 没有必要,因为 file.write 每次调用时都会添加一个新行,并且放置换行符会导致添加额外的行。 尝试在控制台中打印一个列表并检查它。 您可能想查看网络上提供的优秀 Python 教程之一,例如https://docs.python.org/3/tutorial/ 上的 python.org 教程

input_filename = 'input_vocab.txt' output_filename = 'output_vocab.txt' with open(input_filename, 'r') as f: test_words = f.readlines() with open(output_filename, 'w') as f: for item in test_words: f.write(f"{item.strip()}\n")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM