Home > Back-end >  Python - Renaming path using values from a dictionary (for loop)
Python - Renaming path using values from a dictionary (for loop)

Time:08-08

I am renaming a batch of photos. I have a list of the image number (from the camera) and the appropriate name (to be the new name) in a CSV. So far, I have got the csv import in just fine. It imports it as a dictionary with the image name as the "key", and the text as the new name as the "value".

THE PROBLEM: When using the "key" appended to the path, it works just fine. BUT when using the "value", I get an empty list. When calling the type, it says string.

import os
from os.path import dirname
import glob

path = r"C:\Users...\Rename"

All the relevant files are in this "Rename" folder

import csv
with open('Rename\Rename.csv', mode='r') as infile:
reader = csv.reader(infile)
with open('Rename\Rename_new.csv', mode='w') as outfile:
    writer = csv.writer(outfile)
    mydict = {rows[0]:rows[1] for rows in reader}

Print gives:

{'DSC01162.JPG': 'WI-22-62_Bx1-4_5.45-14.45m_Dry', 'DSC01164.JPG': 'WI-22-62_Bx1-4_5.45-14.45m_Wet'}

for key, value in mydict.items():
    value = list(mydict.values())[0]

print(key, value) gives:

DSC01162.JPG WI-22-62_Bx1-4_5.45-14.45m_Dry DSC01164.JPG WI-22-62_Bx1-4_5.45-14.45m_Dry

    old_file = glob.glob(path   "/"   key)
    new_file = glob.glob(path   "/"   value)

Printing the old_file gives the correct: ['C:\...Rename/DSC01162.JPG']

Whereas printing new_file gives and empty list: []

Once I get this correct, I will use:

os.rename(old_file, new_file)

Any ideas on how to get the "new_file" address correct?

I'm not that great on python so some completely different method may be too confusing.

CodePudding user response:

I don't actually got when you're trying to get the old_file and rename new_file (if it is inside or outside the for loop), but I have somethings to point out:

First: it looks like you're on Windows, so try to keep the same folder style: use '\' instead of '/'.

Second: On your for loop, you're already returning the key and values, so that statement value = list(mydict.values())[0] is unecessary.

Then, on your for loop, you could rename the old file names right there:

for key, value in mydict.items():
    old_file = glob.glob(path   "/"   key)
    new_file = glob.glob(path   "/"   value)
    os.rename(old_file, new_file)

CodePudding user response:

Once you have the old and the new names in a dictionary (mydict), you don't need a list(). You can do something like this:

import os

path = r".\rename"
mydict = {'DSC01162.JPG': 'WI-22-62_Bx1-4_5.45-14.45m_Dry', 'DSC01164.JPG': 'WI-22-62_Bx1-4_5.45-14.45m_Wet'}

for key, value in mydict.items():
    old_file = os.path.join(path, key)
    new_file = os.path.join(path, value   '.JPG')
    os.rename(old_file, new_file)

If I understood the question correctly, that would make the job done.

  • Related