0

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)
Spatial Digger
  • 1,883
  • 1
  • 19
  • 37

2 Answers2

0

EDITED Try this:

import os
import shutil

wd = r'C:\Users\Gerrit\Documents\gygaia\Python_scripts\Photos'
def file_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")
        if not 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)
        if not 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

bzimor
  • 1,618
  • 2
  • 14
  • 26
0

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

Maarten Fabré
  • 6,938
  • 1
  • 17
  • 36