如何使用Python组合子文件夹中的文本

如何使用Python组合子文件夹中的文本,python,subdirectory,os.walk,Python,Subdirectory,Os.walk,我有一个包含4个子文件夹的文件夹,并希望合并每个子文件夹中的文本(换句话说,产品应分别为4个合并文本,而不是统一所有子文件夹的完整文本)。 我想使用os.walk,但没有结果 代码如下: 导入操作系统 rootdir=r'xxx\xxx\xxx' 所有文件=[] 对于os.walk(rootdir)中的root、dir和文件: 对于目录中的d: f_out=open(rootdir+d+'combined.txt','w',encoding='utf-8') 对于文件中的文件: allfile

我有一个包含4个子文件夹的文件夹,并希望合并每个子文件夹中的文本(换句话说,产品应分别为4个合并文本,而不是统一所有子文件夹的完整文本)。

我想使用os.walk,但没有结果

代码如下:

导入操作系统
rootdir=r'xxx\xxx\xxx'
所有文件=[]
对于os.walk(rootdir)中的root、dir和文件:
对于目录中的d:
f_out=open(rootdir+d+'combined.txt','w',encoding='utf-8')
对于文件中的文件:
allfiles.append(os.path.join(根,文件))
对于所有文件中的i:
如果i.endswith(r'.txt'):
f_in=open(i,'r',encoding='utf-8')
对于f_in.readlines()中的行:
f_out.写入(行)
f_in.close()
f_out.close()
当你(穿过暴风雨)行走时

您需要将这些文件记录到找到它们的目录中—实际上,当您到达f_out.write()行时,您的方式与读取循环中发生的事情不同步

试试这个:

allFiles2 = {}

for root, dirs, files in os.walk(rootdir):


    for d in dirs:
        f_out = open(rootdir + d + 'combined.txt', 'w', encoding='utf-8')
        allFiles2[os.path.join(root,d)] = []
    
    for name in files:            
        fullName = os.path.join(root, name)
        #At this point, we want to send the file to the correct dictionary position, so use the path defining the dictionary as a search item
        for key in allFiles2:
            if key == fullName[:len(key)]:                
                allFiles2[key].append(os.path.join(root, name))
    
for i1 in allFiles2:  #Looping through the keys (directories) in allFiles2
    with open(i1 + 'combined.txt', 'w', encoding='utf-8') as f_out:
        for i2 in allFiles2[i1]:  #Looping through the files in that directory
            if i2.endswith('.txt'):                
                with open(i2, 'r') as f_in:
                    for line in f_in.readlines():         
                        f_out.write(line)
                    f_out.write("\n")
现在,我不确定您希望输出的文本文件是什么形状,但希望这是一个有用的起点