使用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("%sn" % 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教程,比如python.org上的教程https://docs.python.org/3/tutorial/


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")

相关内容

最新更新