简体   繁体   中英

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'

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 .

This seems very strange . The loop runs only 34199 times but how does the file contain 35545 lines ? I even closed the file immediately after writing using 'test_file.close()'.

My file should only contain 34199 lines . 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. 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/

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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