我有一个包含 7 个文件的文件夹,每个文件里面都有几个文本文件。我打算通读它们并将每个嵌套的文本文件写入一个名为 ZebraAllRaw.txt 的文件中。最后,必须只有一个文件包含这 7 个文件中的每一个中存在的所有文本文件。
这是我写的函数:
def CombineFiles(folder):
with open('D:/ZebraAllRaw.txt', 'a', encoding="utf-8") as OutFile:
for root, dirs, files in os.walk(folder, topdown= False):
for filename in files:
file_path = os.path.join(root, filename)
with open(file_path, 'r', encoding="utf-8") as f:
content = f.read()
new_content = content.replace('\n', '')
OutFile.write(new_content + "\n")
然而,似乎所有的内容都被写入了新文件 9 次,好像它比预期的读取次数更多。
确保您不会附加来自不同运行的文件。
我只在打开时用write替换了文件模式附加
def CombineFiles(folder):
with open('D:/ZebraAllRaw.txt', 'w', encoding="utf-8") as OutFile: # mode "w", not "a"
for root, dirs, files in os.walk(folder, topdown= False):
for filename in files:
file_path = os.path.join(root, filename)
with open(file_path, 'r', encoding="utf-8") as f:
content = f.read()
new_content = content.replace('\n', '')
OutFile.write(new_content + "\n")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句