gpt4 book ai didi

python - Python逐行写入文件

转载 作者:太空宇宙 更新时间:2023-11-04 08:28:11 30 4
gpt4 key购买 nike

这里,我想把每个循环中的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'

关于python - Python逐行写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55130987/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com