Skip to main content
 首页 » 编程设计

python之Python逐行写入文件

2025年05月04日22小虾米

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

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

我也尝试过添加换行符,但它什么也没写。

myfile.write(f'\n') 

请您参考如下方法:

改变这一行:

return str(word_count) 

到

return str(word_count) + '\n' 

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

return f'{word_count}\n'