[英]Combine multiple files from different folders and renamed as folder name to new folder by Python
I have many.txt files and store in different folders, I want to combine multiple files from different folders and renamed as folder name to new folder by python.我有许多.txt 文件并存储在不同的文件夹中,我想组合来自不同文件夹的多个文件,并通过 python 将文件夹名称重命名为新文件夹。
Structure as below:结构如下:
Path xxx路径 xxx
Folder 1文件夹 1
Folder 2文件夹 2
Folder x文件夹 x
After combined and renamed, structure should as below:合并重命名后,结构如下:
New path新路径
folder1.txt (combine 1.txt,2,txt,x.txt in folder1) folder1.txt(在 folder1 中组合 1.txt,2,txt,x.txt)
folder2.txt文件夹2.txt
folder3.txt文件夹3.txt
I have written codes as below to open different folderX.txt, but I get problem about write if to combine different files under same folder to new folderX.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)
Finally I have figured out this request:最后我想出了这个要求:
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.