-1

I would like to make a program that can copy one file(e.g. images) to another directory which contains several folders. By just copying all the images to another directory is easy but I wanted it to be one image copies to one folder.

I looped every single element in both directory and globalized them. I tried copying one file into folder but got errors. I think the main problem I cannot do it is because I lack of the idea how to just copy one file to one folder while looping. I hope you can give me some advice on this matter.

import os
import shutil
path = os.listdir('C:\\Users\\User\\Desktop\\img')
#dst1 = os.path.abspath('C:\\Users\\User\\Desktop\\abc')
idst =  os.listdir('C:\\Users\\User\\Desktop\\abc')

def allimgs():
    counter = 0
    for imgs in path:
        if imgs.endswith('.JPG'):
            counter += 1
             #if hits the 24th images then stop and 
             #copy the first until 24 to another 24 folders one by one
            if counter > 24: 
               break
            else:
                src = os.path.join('C:\\Users\\User\\Desktop\\img',imgs)

def allfolders():                
    for folders in idst:
        if folders.endswith('.db'):
            continue #to skip the file ends with .db
        dst = os.path.join('C:\\Users\\User\\Desktop\\abc',folders)

shutil.copy(allimgs(),allfolders()) #here is where i stuck
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • you should call shutil on src, dst pair. you can do it in one loop, is there a rule to how a image and a folder are matched? imageY goes to folderX? – darc Aug 15 '18 at 19:11
  • @darc hi, thanks for replying so soon. Yes, there's a rule as you mentioned. For example, first image goes to first folder and so forth. – GeographerOnCompSc Aug 15 '18 at 19:44

1 Answers1

0

First of all, make both functions return lists of strings which contain the full paths of the images which will be copied, and the directories to where they will be copied. Afterwards, save the results of allimgs() and allfolders() into variables and loop through them.

Here is how the first function should look like:

def allimgs():
     ret = []
     counter = 0
     for imgs in path:
         if imgs.endswith('.JPG'):
            counter += 1
         #if hits the 24th images then stop and 
         #copy the first until 24 to another 24 folders one by one
         if counter > 24: 
              break
          else:
              src = os.path.join('C:\\Users\\User\\Desktop\\img',imgs)
              ret.append(src)
     return ret

(I left the other one for you as an exercise)

Then loop over them:

for image_path in allimgs():
  for folder_path in allfolders():
    shutil.copy(image_path, folder_path)