python合并路径和文件名_如何通过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. 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. 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))

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值