Copying images from all the directories into another

时间:2018-03-23 00:16:39

标签: python shutil

I have a directory that has about 3000 directories. Each of these 3000 directories has 2 .jpg images. My goes is to move each image from each of these 3000 directories into one separate folders. This is the master directory that has all the images.

Here is a more visual version of my structure:

 -dir1
  -littledir1
    - image1.jpg
    -image2.jpg
  -dir2
    -littledir2
      -image1.jpg
      -image2.jpg
   .
   .
   .
  -dir 3000
    -litledir3000
       -image1.jpg
       -image2.jpg

I attempted to solve this problem with the following code without much success. The keeps running without copying over anything:

My code:

import os
import glob
import shutil

dirpath = '/Volumes/LaCie/lfw/'
dirs = os.listdir(dirpath)

dst_dir = '/Volumes/LaCie/lfw/dstn/'

i = 1

for dirname in dirs:
    if (dirname.endswith('.DS_Store')):
        continue

    for jpgfile in glob.iglob(os.path.join(dirpath, "*.jpg")):
        shutil.copy(jpgfile, dst_dir)
        print (dst_dir)

How can I better approach this problem?

2 个答案:

答案 0 :(得分:1)

Did your print (dst_dir) print? I ran your code but that inner print did not run.

I'm not saying it's a better approach, but this worked for me...obviously you'd need to alter for your situation:

import glob
import os
import shutil

dirpath = 'dir1'
dirs = os.listdir(dirpath)

for dirname in dirs:
    print(dirname)
    os.path.join(dirpath)

    # for file in glob.iglob(os.path.join(dirpath, '*.txt')):
    #     print(file)
    for file in os.listdir(os.path.join(dirpath, dirname)):
        shutil.copy(os.path.join(dirpath, dirname, file), '.')
        print(file)

答案 1 :(得分:0)

if you are on a *nix system use this

cp $(find dirpath -name "*jpg") dst_dir/