0

I am Python beginner, and I am trying to copy multiple images from a folder on our network. I have learned how to copy a single image from our network to my desktop. I have also learned to copy all the images from one folder to another. The problem I am facing is our network folder has over 37,000 images, but my customer needs 1524 specific images.

Here is my functional code that copies one image:

import glob
import shutil
import os

src_dir = 'folder1'
dst_dir = 'folder2'
imageNames = ['image1.png']

for pngfile in glob.iglob(os.path.join(src_dir, imageNames)):
    shutil.copy(pngfile, dst_dir)

This works. It moves the image from one folder to another. However, if I add more images to imageNames, making it a list like imageNames = ['image1.png', 'image2.png'], I experience the following error:

"TypeError: join() argument must be str or bytes, not 'list'"

Someone said on a different thread os.path.join doesn't take a list as an argument. (Python os.path.join() on a list). Instead, he seems to recommend basically converting a list into a string and then separate the file names using the split method. Then later in my loop, add a * ("splat operator") to imageNames like this:

import glob
import shutil
import os

src_dir = "folder1"
dst_dir = "folder2"
imageNames = "'image1.png', 'image2.png'".split(",")

for pngfile in glob.iglob(os.path.join(src_dir, *imageNames)):
    shutil.copy(pngfile, dst_dir)

When I run this code, I do not receive the "not 'list'" error, but then nothing happens--the files are not copied, not even the first image.

Would you please give me some advice on how to proceed?

Thank you!

1 Answers1

0

The use case in the question you have linked is a completely different one and not applicable to your case. It doesn't talk about multiple files, but only about a path, where each part of the path is an entry in a list.

In your case you just need to loop over your list and then copy each file individually (no need for glob):

import shutil
import os

src_dir = "folder1"
dst_dir = "folder2"
imageNames = ['image1.png', 'image2.png']
for imageName in imageNames:
    shutil.copy(os.path.join(src_dir, imageName), dst_dir)
Joshua Wolff
  • 2,687
  • 1
  • 25
  • 42
FlyingTeller
  • 17,638
  • 3
  • 38
  • 53
  • FlyingTeller, thank you so much! I noticed that the program did not copy all of my images. It stopped working when it did not find a missing image, so I added a try / except: pass to my program and it worked! – Jason Honeycutt Mar 12 '18 at 18:42
  • @JasonHoneycutt You could also use the `os.path.isfile(....)` to make sure that an image is there before trying to do something with it – FlyingTeller Mar 12 '18 at 18:44