Move files from the lowest sub directory up one level
The script below searches a directory for the lowest sub directory (= without sub directories) recursively and moves all found files in the folder(s) up one level, as literally asked for in The goals is to move files out of the lowest level folder, back up one directory:
#!/usr/bin/env python2
import shutil
import os
import sys
directory = sys.argv[1]
for root, dirs, files in os.walk(directory):
for dr in dirs:
dr = root+"/"+dr
# find folders without subfolders (= lowest level)
if len(next(os.walk(dr))[1]) == 0:
# direct superior directory
up = dr[:dr.rfind("/")]
# move files from lowest level one level up
for f in os.listdir(dr):
shutil.move(dr+"/"+f, up+"/"+f)
To use:
- Copy the script into an empty file, save it as
reorganize.py
Run it by the command:
python /path/to/reorganize.py <directory_to_reorganize>
If the name of your directory (to reorganize) contains spaces, use quotes:
python /path/to/reorganize.py '<directory_to_reorganize>'
EDIT
As mentioned in a comment, with a little change, the script can be used to only move files from a folder name up one level. The moste efficient way is to do that directly after
for dr in dirs:
Then the script would be:
#!/usr/bin/env python3
import shutil
import os
import sys
directory = sys.argv[1]
for root, dirs, files in os.walk(directory):
for dr in dirs:
if dr == "<folder_name>":
dr = root+"/"+dr
# direct superior directory
up = dr[:dr.rfind("/")]
# move files from lowest level one level up
for f in os.listdir(dr):
shutil.move(dr+"/"+f, up+"/"+f)
.jpg
's are in the same folder you can usemv -t ../ *.jpg
....if they on different folders then your command will move each of them to their respective parent directories.do you want to move them to the same directory?cd photos; mv *jpg ../
ormv /path/to/photos/*jpg /path/to
won't do? Do you have multiple directories?