简体   繁体   English

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

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

I have a list 'test_words' of length 34199 and I wish to write each element of this list into a file 'test_vocab.txt'我有一个长度为 34199 的列表“test_words”,我希望将此列表的每个元素写入文件“test_vocab.txt”

This is my code to achieve the same :这是我实现相同目标的代码:

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

Now the problem is , even though the list contains only 34199 elements and even when I print out 'count' in each iteration of the loop , it goes only up to 34199 , the actual file contains 35545 lines .现在的问题是,即使列表只包含 34199 个元素,即使我在循环的每次迭代中打印出 'count',它也只能达到 34199,实际文件包含 35545 行。

This seems very strange .这似乎很奇怪。 The loop runs only 34199 times but how does the file contain 35545 lines ?循环仅运行 34199 次,但文件如何包含 35545 行? I even closed the file immediately after writing using 'test_file.close()'.我什至在使用“test_file.close()”写入后立即关闭了文件。

My file should only contain 34199 lines .我的文件应该只包含 34199 行。 Can someone please help me resolve this issue ?有人可以帮我解决这个问题吗? I don't know how to proceed further我不知道如何进一步

try the following:尝试以下操作:

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

The reason of you extra lines you´re getting comes from the line break character you are placing.你得到额外行的原因来自你放置的换行符。 It is not necessary since file.write will add a new line each time it is called, and placing a line break character will result in extra lines added.没有必要,因为 file.write 每次调用时都会添加一个新行,并且放置换行符会导致添加额外的行。 Try printing a list in a console and check it out.尝试在控制台中打印一个列表并检查它。 You may want to check one of the good python tutorials available in the web such as the python.org one at https://docs.python.org/3/tutorial/您可能想查看网络上提供的优秀 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