0

我有许多 .txt 文件并存储在不同的文件夹中,我想组合来自不同文件夹的多个文件并通过 python 将文件夹名称重命名为新文件夹。

结构如下:

路径 xxx

文件夹 1

  • 1.txt
  • 2.txt
  • x.txt

文件夹 2

  • 1.txt
  • 2.txt
  • x.txt

文件夹 x

  • 1.txt
  • 2.txt
  • x.txt

合并重命名后,结构如下:

新路径

folder1.txt(在 folder1 中组合 1.txt,2,txt,x.txt)

文件夹2.txt

文件夹3.txt

我已经编写了如下代码来打开不同的folderX.txt,但是如果将同一文件夹下的不同文件组合到新的folderX.txt,我会遇到问题。

import os
path = "/Users/guozhao/Downloads/2021-02-04 10-12-07_NSGI/"

for root,dirs,files in os.walk(path):
    for dir in dirs:
        write_files = [os.path.join(dir) + '.txt']
        for wf in write_files:
            with open(wf,'w') as outfile:
                for root,dirs,files in os.walk(path):
                    for file in files:
                        read_files = os.path.join(root,file)
                        if os.path.isdir(read_files):
                            for rf in read_files:
                                with open(rf,'r') as infile:
                                    outfile.write(infile)
4

1 回答 1

0

最后我想出了这个要求:


import os
path = input('Please input your file path: ')

for root,dirs,files in os.walk(path):
    for dir in dirs:
        if dir == ".DS_Store":
            continue
        write_files = os.path.join(dir) + '.txt'
        with open(write_files,'w') as outfile:
            read_path = os.path.join(root,dir)+'/'
            for readfile in os.listdir(read_path):
                if readfile == ".DS_Store":
                    continue
                with open(os.path.join(read_path,readfile),'r') as infile:
                    infile_content=infile.read()
                    outfile.write(infile_content)

于 2021-03-15T04:51:05.820 回答