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/.
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.
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'))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With