Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python rename files reading names from csv file

Hi there i've been trying to adapt this to my needs but I'm just a newbe in python, I have a csv file with multiple columns and rows, important columns are 1 = old name of file, and 2 = new name of file, so I need to go the directory where the files listed in csv file are and rename them to the new name of column 2, as I say I've tried many things without success, I paste the last code I've made so you have an idea:

import os, unicodecsv as csv, sys

IDs = {}

#open and store the csv file
with open('documentos_corpus_ladino.csv','rb') as csvfile:
        timeReader = csv.reader(csvfile, delimiter = ',')

        # build a dictionary with the associated IDs
        for row in timeReader:
              IDs[ row[0] ] = row[1]

# #get the list of files
path = 'txt_orig/'
tmpPath = 'txt_tmp/'
for filename in os.listdir('txt_orig/'):
    oldname = filename
    newname = filename.replace(oldname, csvfile.next().rstrip().split(",")[1])
    os.rename(path + filename, tmpPath + newname)

Thanks a lot.

like image 813
Andrés Chandía Avatar asked Feb 14 '23 15:02

Andrés Chandía


1 Answers

This will rename each matching file, and report any errors trying to rename. It will not attempt to move non-existent files.

import os, unicodecsv as csv
# open and store the csv file
IDs = {}
with open('documentos_corpus_ladino.csv','rb') as csvfile:
    timeReader = csv.reader(csvfile, delimiter = ',')
    # build dictionary with associated IDs
    for row in timeReader:
        IDs[row[0]] = row[1]
# move files
path = 'txt_orig/'
tmpPath = 'txt_tmp/'
for oldname in os.listdir(path):
    # ignore files in path which aren't in the csv file
    if oldname in IDs:
        try:
            os.rename(os.path.join(path, oldname), os.path.join(tmpPath, IDs[oldname]))
        except:
            print 'File ' + oldname + ' could not be renamed to ' + IDs[oldname] + '!'
like image 121
Pi Marillion Avatar answered Feb 24 '23 04:02

Pi Marillion