简体   繁体   中英

Write to file line by line Python

Here, I want to write the word_count in each loop line by line to the file. However, they are written all back to back.

import os
import string
def remove_punctuation(value):
    result = ""
    for c in value:
        # If char is not punctuation, add it to the result.
        if c not in string.punctuation and c != '،' and c != '؟' and c !   = '؛' and c != '«' and c != '»':
            result += c
    return result
def all_words(file_path):
    with open(file_path, 'r', encoding = "utf-8") as f:
        p = f.read()
        p = remove_punctuation(p)
        words = p.split()
        word_count = len(words)
        return str(word_count)
myfile = open('D:/t.txt', 'w')
for root, dirs, files in os.walk("C:/ZebRa", topdown= False):
    for filename in files:
        file_path = os.path.join(root, filename)
        f = all_words(file_path)
        myfile.write(f)
        break
myfile.close()

I have also tried to add newline, but instead, it writes nothing.

myfile.write(f'\n')

Change this line:

return str(word_count)

to

return str(word_count) + '\n'

If you're using python 3.6+, you could also try:

return f'{word_count}\n'

You can write a newline character at the end of each iteration:

for root, dirs, files in os.walk("C:/ZebRa", topdown= False):
    for filename in files:
        file_path = os.path.join(root, filename)
        f = all_words(file_path)
        myfile.write(f)
        break
    myfile.write('\n')

When you us file.write() try using this instead:

myfile.write(f+"\n")

This will add a new line after every iteration

For your code to work, however, you need to iterate in a for loop, like this:

for string in f:
    file.write(string+"\n")

I hope this helps

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