如何通过Python合并名称相同但位于不同文件夹中的文件中的内容? [英] How to merge content from files with same name but in different folders by Python?

查看:953
本文介绍了如何通过Python合并名称相同但位于不同文件夹中的文件中的内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python合并来自不同TXT文件的内容,但是挑战在于,我只需要合并来自不同文件夹的相同文件名的内容.以下是屏幕截图供您参考:

I'm trying to merge content from different TXT files by using Python, but the challenge is I need to only merge content from the same file names coming from different folders. Here's a screenshot for your reference:

到目前为止,我可以打印出所有文件名及其完整路径:

So far, I can print out all the file names with their full paths:

import os

for root, dirs, files in os.walk(".", topdown=False):
    for file in files:
        if file.endswith(".txt"):
            filepath = os.path.join(root, file)
            print (filepath)

但是,如何使用Python仅合并具有相同名称的文件...仍在研究中.让我知道您是否知道答案,或者为我指出一种进行更多研究的方法.非常感谢您,节日快乐!

However, how could I use Python to only merge files with the same name...still researching. Let me know if you know the answer, or point me a way to research more. Thank you very much and happy holidays!

推荐答案

import os

# create a dictionary with file names as keys
# and for each file name the paths where they
# were found
file_paths = {}
for root, dirs, files in os.walk('.'):
    for f in files:
        if f.endswith('.txt'):
            if f not in file_paths:
                file_paths[f] = []
            file_paths[f].append(root)

# for each file in the dictionary, concatenate
# the content of the files in each directory
# and write the merged content into a file
# with the same name at the top directory
for f, paths in file_paths.items():
    txt = []
    for p in paths:
        with open(os.path.join(p, f)) as f2:
            txt.append(f2.read())
    with open(f, 'w') as f3:
        f3.write(''.join(txt))

这篇关于如何通过Python合并名称相同但位于不同文件夹中的文件中的内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆