[英]Write to file line by line Python
在这里,我想将每个循环中的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'
您可以在每次迭代的末尾写一个换行符:
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')
当您使用file.write()时,请尝试使用以下代码:
myfile.write(f+"\n")
每次迭代后都会添加新行
为了使代码正常工作,您需要在for循环中进行迭代,如下所示:
for string in f:
file.write(string+"\n")
我希望这有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.