簡體   English   中英

合並來自不同文件夾的多個文件,並通過 Python 將文件夾名稱重命名為新文件夾

[英]Combine multiple files from different folders and renamed as folder name to new folder by Python

我有許多.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)

最后我想出了這個要求:


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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM