Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively move all files on subdirectories to another directory in Python

The title explains what I am after. Note that the sub directories won't contain any directories only files (*.JPG). Essentially, just moving everything up one level in the file tree.

For example, from ~/someDir/folder1/* , ~/someDir/folder2/* , ... , ~/someDir/folderN/*. I want all of the contents of the sub directories brought up to ~/someDir/.

like image 460
Xlqt Avatar asked Oct 27 '25 08:10

Xlqt


2 Answers

shutil.move is a good option to move files.

import shutil
import os

source = "/parent/subdir"
destination = "/parent/"
files_list = os.listdir(source)
for files in files_list:
    shutil.move(files, destination)

For Recursive move, you can try shutil.copytree(SOURCE, DESTINATION). it just copies all files and if needed you can manually cleanup the source directory.

like image 198
Sunil Kumar Avatar answered Oct 28 '25 23:10

Sunil Kumar


Also, You can achieve something similar using Pathlib.

from pathlib import Path
def _move_all_subfolder_files_to_main_folder(folder_path: Path):
    """
    This function will move all files in all subdirectories to the folder_path dir.
    folder_path/
        1/
            file1.jpg
            file2.jpg
        2/ 
            file4.jpg
    outputs:
    folder_path/
        file1.jpg
        file2.jpg
        file4.jpg
    """
    if not folder_path.is_dir():
        return

    for subfolder in folder_path.iterdir():
        for file in subfolder.iterdir():
            file.rename(folder_path / file.name)

Usage would be:

_move_all_subfolder_files_to_main_folder(Path('my_path_to_main_folder'))
like image 45
Amir Pourmand Avatar answered Oct 28 '25 21:10

Amir Pourmand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!