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/dir/dir/dir/file3.jpg
I would like to copy and rename each image based on the folder structure, so:
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_dir_dir_dir_file3.jpg
So far I have this, but I could do with some help/pointers.
import os
import sys
for dirname, dirnames, filenames in
os.walk('/Users/Gerrit/Documents/gygaia/Python_scripts/Photos', topdown=True):
# print path to all subdirectories first.
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
# print path to all filenames.
for filename in filenames:
#print(os.path.join(dirname, filename))
path = os.path.join(dirname, filename)
#replace path string '/' with '_'
#replace path string '\' with '_'
print(path.replace('/', '_'))
edited
import os, subprocess
from shutil import copyfile
os.chdir('C:\\Users\Gerrit\Documents\gygaia\Python_scripts\Photos')
root_dir = os.getcwd()
def file_mover():
for root, dirs, files in os.walk(os.getcwd()):
for file in files:
if file.endswith(".jpg"):
print(os.path.join(root, file))
src = (os.path.join(root, file))
# remove the cwd from the path
path = src.replace(root_dir, "")
# replace \\ with _ in the paths
path = path.replace("\\", "_")
file_name = path.replace("_", "",1)
# copy and rename the jpg files including the file path
os.chdir("..")
dst = os.getcwd() + "\\Photos_mirror"
copyfile(src, dst)
file_mover()
Old EDIITED I've managed to get this far, but the copy file command is not working, its saying permissions error 12, I've tried opening python IDE with admin rights (windows) but it still wont work, here's the code:
###Script to copy images and rename them by their former directory location###
import os, sys, subprocess, glob
from shutil import copyfile
def file_mover():
#First set working directory - we don't want to rename everything!
os.chdir('C:\\Users\Gerrit\Documents\gygaia\Python_scripts\Photos')
path = os.getcwd()
print (path)
for dirname, dirnames, filenames in os.walk(path, topdown=True):
# print path to all subdirectories first.
print("loop 1")
for subdirname in dirnames:
print(os.path.join(dirname, subdirname))
path2 = (os.path.join(dirname, subdirname))
# remove the cwd from the path
path = path2.replace(path, "")
# replace \\ with _ in the paths
path = path.replace("\\", "_")
path = path.replace("_", "",1)
path = path + ("_")
print("loop 2")
# copy and rename the jpg files including the file path
os.chdir("..")
dst = os.getcwd() + "\\Photos_mirror"
src = dirname +("\\")
copyfile(src, dst)