Home > OS >  how can I move files from subfolder/sub-subfolder recursively ? [python]
how can I move files from subfolder/sub-subfolder recursively ? [python]

Time:09-16

I have problems solving a task. Below you can see my code. I want to work with sub-sub-folders too but my code only moves the sub-folders. How can I do this recursively that it moves all folders in main folder?

path = (r"C:\Users\Desktop\testfolder")
os.chdir(path)
all_files = list(os.listdir())
outputs = os.getcwd()
for files in all_files:
    try:
        inputs = glob.glob(files   "\\*")
        for a in inputs:
            shutil.move(a, outputs)
    except:
        pass

for files in os.listdir("."):
    dir_folder = files[:32]
    if not os.path.isdir(dir_folder):
        try:
            os.mkdir(dir_folder)
        
        except:
            pass

CodePudding user response:

Here is the new code, that will maintain the folder structure in the output folder as it was in the input folder

from pathlib import Path
import shutil
import os
for path, dir_folder, files in os.walk('./test_folder'):
    for file in files:
        full_path = os.path.join(path,file)
        ## Create the path to the subfolder
        sub_folder_path = '/'.join(path.split('/')[2:])
        # Create output path by joining subfolder path and output directory
        output_path = os.path.join(outputs, sub_folder_path)
        # Create the output path directory structure if it does not exists, ignore if it does
        Path(output_path).mkdir(parents=True, exist_ok=True)
        # Move file
        shutil.move(full_path, output_path)

You can use os.walk to recursively visit each folder and sub folder and then move all the files in that folder.

import shutil
import os
for path, dir_folder, files in os.walk(input_folder):
    for file in files:
        full_path = os.path.join(path,file)
        move_path = os.path.join(output_path,file)
        print(move_path)
        shutil.move(full_path, move_path)
        print(file)

Where output_path is the path to the folder you move to move the files to.

This will not create the same folder structure in output folder, just move all the files there, do you also want to maintain structure in output folder? If so, I can edit my answer to reflect that

  • Related