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