python - 将多个嵌套文件变成一个文件(连接它们)
问题描述
我有一个包含 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替换了文件模式append
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")
推荐阅读
- angularjs - Unable to write a pdf base64 encoded file into android and ios device using ionic-native/file plugin
- docker - 将文件从 GCP 复制到 docker 容器
- c# - 按嵌套列表对列表进行分组并删除与组不对应的元素
- java - “节点流”和“过滤流”有什么区别?
- c# - 问:在 wpf 中的窗口之间传递字符串
- javascript - 如何构建动态包含标题的语义用户界面下拉列表?
- reactjs - TypeError: eleves.map 不是函数 React/Spring-boot 无法显示 @ManyToOne 关系
- c# - 如何使用 .NET HttpClient 获取服务器证书无效的原因?
- sql - 在 Oracle 中使用 regexp_like 使用一系列值匹配多个字符串条件
- python - 在 while 循环之外访问变量值