How to copy first n images from a directory to another directory?

Question:

I need to copy the first 1400 images from one directory to another. The code I’ve seen:

fnames = ['{}.app_res_model.tiff'.format{i} for i in range(1400)]
for fname in fnames:
    src = os.path.join(dataset_dir, fname)
    dst = os.path.join(train_dir_input, fname)
    shutil.copyfile(src, dst)

As my images are usually labelled "0app_res_model.tiff", this usually works. However I had to delete some images because of poor quality so that now when the loop gets to 18app_res_model.tiff" it breaks because it cannot find the image.

So my question is: how can I adapt this loop so that it’s no longer about the number in the front but simply the first 1400 images in the dataset?

Thanks

Asked By: Gonde94

||

Answers:

You also need to allow for the possibility that are not as many as 1,400 files in the source directory. How about something like this:

from glob import glob
from os.path import join, basename
from shutil import copyfile

SOURCE_DIR = 'foo'
TARGET_DIR = 'bar'

for tiff in glob(join(SOURCE_DIR, '*.app_res_model.tiff'))[:1_400]:
    copyfile(tiff, join(TARGET_DIR, basename(tiff)))
Answered By: Stuart
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.