在这里,我想逐行将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")
我希望这有帮助