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