逐行写入文件Python [英] Write to file line by line Python

查看:88
本文介绍了逐行写入文件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'

这篇关于逐行写入文件Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆