Python rename files reading names from csv file

后端 未结 3 1525
醉话见心
醉话见心 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 06:35

    You should make use of the dictionary IDs that you created from your CSV:

    for filename in os.listdir(path):
        oldname = filename
        newname = IDs[oldname]
        os.rename(path + filename, tmpPath + newname)
    

    But you probably should use some kind of error checking.. (Edit As the other answers have pointed out it's best to use also os.path.join) Maybe something along these lines:

    failed = []
    for oldname in os.listdir(path):
        try:
            old = os.path.join(path, oldname)
            new = os.path.join(tmpPath, IDs[oldname])
            os.rename(old, new)
        except KeyError, OSError:
            failed.append(oldname)
    
    print failed
    

提交回复
热议问题