简体   繁体   English

如何通过Python合并来自同名但位于不同文件夹中的文件的内容?

[英]How to merge content from files with same name but in different folders by Python?

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.我正在尝试使用 Python 合并来自不同 TXT 文件的内容,但挑战是我只需要合并来自不同文件夹的相同文件名的内容。 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)

However, how could I use Python to only merge files with the same name...still researching.但是,我如何使用 Python 仅合并具有相同名称的文件……仍在研究中。 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))

You should do something like below, note: code not tested.您应该执行以下操作,请注意:代码未经测试。

import os

mapped_files = {}

for path, subdirs, files in os.walk("."):
    for file in files:
        if file.endswith(".txt"):
            if file in mapped_files:
                existing = mapped_files[file]
                mapped_files[file] = existing.append(path)
            else:
                mapped_files[file] = [path]

for key in mapped_files:
    files = mapped_files[key]
    first_f = os.path.join(path, files[0])
    with open(first_f, "a+") as current_file: 
        for path in files[1:]: # start at the second index
            f = os.path.join(path, key)
            content = open(f,"r").read()
            current_file.write(content) # add all content to the first file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何区分两个不同文件夹中具有不同扩展名的同名文件? Python - How to differentiate files with same name with different extension from two different folders? Python 使用 Python 合并不同文件夹中的 CSV 个文件 - Merge CSV files in different folders using Python 如何将 5 个同名但位于 5 个不同文件夹中的 Excel 文件合并? - How to combine 5 Excel files with the same name but in 5 different folders? python 以编程方式从不同文件夹导入相同的文件名 - python import the same file name programatically from different folders PyCharm 导入不同文件夹中同名文件 - PyCharm Import files with same name in different folders 如何使用Python合并来自不同工作簿的多个同名excel工作表并保存到新的excel工作簿中 - How to merge multiple excel sheet with the same name from different workbooks and save into a new excel workbook using Python python 在不同文件夹中查找相同文件名,并利用两个文件完成某项任务 - Find same file name in different folders, and utilize two files for a certain task in python 如何合并文件中的内容? - How to merge the content from files? 查找名称相同但内容不同的文件 - Find files with same name but different content 如何从2个同名的python文件中加载2个同名的函数? - How to load 2 functions with the same name from 2 python files with the same name?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM