Python rename files reading names from csv file

后端 未结 3 1552
醉话见心
醉话见心 2021-01-07 06:28

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

3条回答
  •  梦谈多话
    2021-01-07 07:00

    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] + '!'
    

提交回复
热议问题