逐行写入文件Python

逐行写入文件Python

问题描述:

在这里,我想将每个循环中的word_count逐行写入文件.但是,它们都是背靠背写的.

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

更改此行:

return str(word_count)

return str(word_count) + '\n'

如果您使用的是python 3.6+,则还可以尝试:

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

return f'{word_count}\n'