Krithika Raghavendran
Krithika Raghavendran

Reputation: 457

How to move specific files from one subdirectory to the other

This is what my directory structure looks like:

 Dataset
   ---> Images
          ----> n02085620-Chihuahua
                    ---> n02085620_01.jpg
                    ---> n02085620_02.jpg
                    .
                    .
                    . (~ 150+ files)
          ----> n02086646-Blenheim-Spaniel
          ----> n02087046-Toy-Terrier
          .
          .
          .
          (120 Folders)
   ---> Training
          ---> Chihuahua
          ---> Blenheim Spaniel
          ---> Toy Terrier
          .
          .
          .
          (120 Empty Folders)

I also have a list of file paths:

train_file_list = ['n02085620-Chihuahua/n02085620_5927.jpg', ... ', 'n02086646-Blenheim_spaniel/n02086646_1342.jpg', ..., 'n02087046-toy_terrier/n02087046_3490.jpg' ]

This list has 12,000 items, 100 file-paths for each of the 120 breeds in order i.e., the first 100 images are Chihuahua, next 100 are Blenheim-Spaniel and so on.

I also have a dictionary mapping dog_id to dog_breed constructed from two respective lists:

n02097658: Chihuahua
n02092002: Japanese Spaniel
n02099849: Maltese
.
.
.
(120 key-value pairs)

I am trying to loop through my file-path list and for every file-path that begins with dog_id, I want to move that file to its respective folder under Dataset/Training using the dictionary for mapping it to the breed.

Here's the code I've tried on Jupyter Notebook that doesn't seem to be working. Where am I going wrong? Please help!!!

root = "/Users/krithika/Desktop/GitHub Repositories/The-Pup-Files"

os.chdir(root)

for d_id, file in zip(dog_ids, train_file_list):
    if file.startswith(d_id):
        shutil.copy((root + "/Dataset/Images/" + file), (root + "/Dataset/Training/" + dog_ids_breeds[d_id]))

Upvotes: 0

Views: 52

Answers (1)

Wil
Wil

Reputation: 26

Why don't you try nesting your loops, like this:

for d_id in dog_ids:
    for file in train_file_list:
        if file.startswith(d_id):
            shutil.copy((root + "/Dataset/Images/" + file), (root + "/Dataset/Training/" + dog_ids_breeds[d_id]))

Hope this works! :-)

Upvotes: 1

Related Questions