Renaming Files Base On The File Structure
I have a directory structure containing folders and files: dir/dir/dir/file1.jpg dir/dir/dir/file2.jpg dir/dir/dir/file3.jpg dir/dir/dir/dir/file1.jpg dir/dir/dir/dir/file2.jpg dir
Solution 1:
EDITED Try this:
import os
import shutil
wd = r'C:\Users\Gerrit\Documents\gygaia\Python_scripts\Photos'deffile_mover():
for path, dirs, files in os.walk(wd):
for file in files:
if file.endswith(".jpg"):
src = os.path.join(path, file)
#Assuming 'Photos_mirror' folder is in folder which images are located
dst = os.path.join(os.getcwd(), "Photos_mirror")
ifnot os.path.exists(dst): #Checks 'Photos_mirror' folder exists otherwise creates
os.makedirs(dst)
new_name = src.replace(wd+'\\', '').replace('\\', '_')
new_dst = os.path.join(dst, new_name)
ifnot os.path.isfile(new_dst):
shutil.copy(src, dst)
old_dst = os.path.join(dst, file)
#Assuming your /dir/dir/... structure is inside of your working directory (wd)
os.rename(old_dst, new_dst)
else:
continue
file_mover()
If you have questions or I misunderstand your problem, feel free to comment
Solution 2:
You could use pathlib.Path
to simplify most of this
I could not test this, but something like this should work
from pathlib import Path
import shutil
start_path = Path(<start_dir>)
dest_dir = Path(<dest_dir>)
for file in start_path.glob('**/*.jpg'):
new_name = dest_dir.joinpath('_'.join(file.parts))
print('renaming %s to %s' % (str(file), str(new_name)))
# file.rename(new_name) # move# shutil.copy(file, new_name) # copy, newer python# shutil.copy(str(file), str(new_name)) # copy, older python
Remove the correct # when the test succeeds
Post a Comment for "Renaming Files Base On The File Structure"