从根目录中的子目录中移出文件

时间:2016-04-14 05:26:03

标签: python file directory

我有以下文件夹层次结构:

----Folder
------Subfolders
-----------Sub-sub-folder
--------------Files

所以我有多个子文件夹,并且在每个子文件夹中我都有一个包含多个文件的子子文件夹,我想从子文件夹向上移动到子文件夹

执行此操作最简单,最脏的方法:只需将文件从子子文件夹复制到子文件夹,然后删除子子文件夹。 但如果您知道更好的pythonic方式,请告诉我

2 个答案:

答案 0 :(得分:1)

import os
import shutil

Subfolders = os.listdir('Folder')            # get the list of Subfolders
for Subfolder in Subfolders:                 # iterate thru each subfolder
    sfiles = os.listdir('Folder/Subfolder/Sub-sub-folder') # get list of file at each Subfolder/Sub-sub-folder
        for sfile in sfiles:
            shutil.move(sfile, Subfolder) # each file in subfolder is moved to subfolder

答案 1 :(得分:1)

import os
import shutil

path = 'Folder'                                                    #set target folder

Subfolders = os.listdir(path)                                      #get list of subfolders 

for Subfolder in Subfolders:                                       #for each listed subfolder
    Subsubfolders = os.listdir(path+'/'+Subfolder)                 #get list of sub-subfolders
    for Subsubfolder in Subsubfolders:                             #and cycle through them
        sfiles = os.listdir(path+'/'+Subfolder + '/' Subsubfolder) #to get list of files in every sub-subfolder
        for sfile in sfiles:                                       #and move every listed file
            shutil.move(path+'/'+Subfolder+'/'+'/'+ Subsubfolder+'/'+sfile, path)