Niminim
Niminim

Reputation: 678

Moving files according to a csv file

Assuming I have 2 folders - Images A, and Images B, and there's a bunch of images in each folder. These folders have the following structure:

Images A
-- 1111,jpg
-- 2222.jpg
-- 3333.jpg
-- 4444.jpg
-- 5555.jpg

Images B
-- 6666,jpg
-- 7777.jpg
-- 8888.jpg
-- 99999.jpg

Plus, I have a csv with a list of image names. Thing is, I need to move those images ( from imagesA/B) to a new empty folder, let's call it - New Folder. Question is how do I do it?

The csv file looks like this:

blabla/blabla2/blabla3/2222.jpg
blabla/blabla2/blabla3/7777.jpg

(Needless to mention that I don't have all the blabla directories, I should use split and forget about all the blabla).

Upvotes: 1

Views: 1398

Answers (1)

The csv and module can help.

Assuming the .csv file is a simple list of relative paths of image files, that is of the form:

1111.png
2222.png
...

The csv.reader method allows you to read each row of the csv sheet. Then, you use os.rename([past], [new]) to check if that file is in folder A or B and then write it to the New Folder. Be careful of FileExistsError in case of name clashes. Here is the sample code.

import csv
import os

with open('csvmove.csv', newline='') as csvfile:
    linereader = csv.reader(csvfile, delimiter=',')
    for row in linereader:
        name = row[0]
        # Deal with the A folder
        try:
            os.rename('A/' + name, 'New folder/' + name)
            print(name + " moved to new folder.")
        except FileNotFoundError:
            pass # Not found in A
        # Deal with the B folder
        try:
            os.rename('B/' + name, 'New folder/' + name)
            print(name + " moved to new folder.")
        except FileNotFoundError:
            pass # Not found in B
        except FileExistsError:
            pass # Name clash

If you want to customize your .csv file, modify how the name = row[0] line as the row is an array of values in a given .csv row. You can also handle cases where both A/1111.png and B/1111.png occurs.

Please note this code uses relative paths, so if you want the blabla/blabla2/blabla3/... to work you may need to create the folders blabla/blabla2/blabla3/ from the folder containing the python file.

Upvotes: 1

Related Questions