逐行写入文件

问题描述 投票:1回答:3

在这里,我想逐行将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')
python file
3个回答
3
投票

改变这一行:

return str(word_count)

return str(word_count) + '\n'

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

return f'{word_count}\n'

1
投票

您可以在每次迭代结束时编写换行符:

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

1
投票

当你我们file.write()尝试使用它:

myfile.write(f+"\n")

这将在每次迭代后添加一个新行

但是,要使代码工作,您需要迭代for循环,如下所示:

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

我希望这有帮助

© www.soinside.com 2019 - 2024. All rights reserved.