我的python脚本以递归方式重命名文件,但失败了

时间:2017-12-24 12:52:38

标签: python dictionary for-loop subprocess substring

我正在尝试递归重命名目录中的文件,因此我编写了一个python脚本来处理重命名。理想情况下,脚本应该能够转为

Nicholass-MacBook-Air-2:RenameXtalTest nick$ ls
RC000870-C1_02-E0_00.jpg
RC000870-G7_01-E0_99.jpg
rename.py

#!/usr/bin/python
oldname = 'RM01_03_000_0213_Proj1_Clon1_RC_0000RC000870_010_171222_01_03_02_E0_00_031_001_RAI.jpg'  #manually set an old name
rowdic = {"01" : "A", "02" : "B", "03" : "C", "04" : "D", "05" : "E", "06" : "F", "07" : "G", "08" : "H"} #dictionary to translate oldname char 59 to 61
coldic = {"01" : "1", "02" : "2", "03" : "3", "04" : "4", "05" : "5", "06" : "6", "07" : "7", "08" : "8", "09" : "9", "10" : "10", "11" : "11", "12" : "12"} #dictionary to translate oldname char 56 to 58
subwdic = {"01" : "1", "02" : "2", "03" : "3"} #dictionary to translate oldname char 62 to 64

newname = oldname[36:44]+"-"+rowdic[oldname[59:61]]+coldic[oldname[56:58]]+"_"+subwdic[oldname[62:64]]+"-"+oldname[65:70]+".jpg" #definition for how to shorten, rearrange, and swap out some parts of oldname

print newname

我可以让rename.py使用Python中的 单个名称 ,如果它看起来像这样:

#!/usr/bin/python
import os
rowdic = {"01" : "A", "02" : "B", "03" : "C", "04" : "D", "05" : "E", "06" : "F", "07" : "G", "08" : "H"} #dictionary to translate oldname char 59 to 61
coldic = {"01" : "1", "02" : "2", "03" : "3", "04" : "4", "05" : "5", "06" : "6", "07" : "7", "08" : "8", "09" : "9", "10" : "10", "11" : "11", "12" : "12"} #dictionary to translate oldname char 56 to 58
subwdic = {"01" : "1", "02" : "2", "03" : "3"} #dictionary to translate oldname char 62 to 64
for oldname in os.listdir("."): #get list of all oldnames in current directory
    newname = oldname[36:44]+"-"+rowdic[oldname[59:61]]+coldic[oldname[56:58]]+"_"+subwdic[oldname[62:64]]+"-"+oldname[65:70]+".jpg" #definition for how to shorten, rearrange, and swap out some parts of oldname
    os.rename(oldname, newname) #command to change all old names to new names

但是一旦我尝试让脚本在 Unix中的多个文件 上工作 - 它就会失败。这是我在前面提到的脚本尝试:

Nicholass-MacBook-Air-2:RenameXtalTest nick$ ./rename.py 
Traceback (most recent call last):
  File "./rename.py", line 7, in <module>
    newname = oldname[36:44]+"-"+rowdic[oldname[59:61]]+coldic[oldname[56:58]]+"_"+subwdic[oldname[62:64]]+"-"+oldname[65:70]+".jpg"
KeyError: ''

这是我尝试运行时遇到的错误:

permit

有人可以帮助我理解错误的含义,以及我可以做些什么来解决它?

1 个答案:

答案 0 :(得分:0)

@mooiamaduck和我的评论组合给出了这段代码:

for oldname in os.listdir("."):
    if len(oldname) < 70:
        continue 
    newname = oldname[36:44]+"-"+rowdic[oldname[59:61]]+coldic[oldname[56:58]]+"_"+subwdic[oldname[62:64]]+"-"+oldname[65:70]+".jpg"
    os.rename(oldname, newname) #command to change all old names to new names

问题基本上在于您还处理的文件没有您希望重命名的特定文件名格式。 (例如,您的...rename.py。)oldname[62:64]然后转换为空字符串,然后您将其用作{{1}的密钥导致空字符串subwdic

这里提出的简单修复方法是仅考虑至少包含70个字符的文件名。当然,更好的解决方案是对文件名进行适当的检查,看它是否与您的模式匹配,但这对您的特定用例来说会很好。