【发布时间】:2017-12-24 12:52:38
【问题描述】:
我正在尝试递归重命名目录中的文件,因此我编写了一个 python 脚本来处理重命名。所以理想情况下,脚本应该可以转这个
Nicholass-MacBook-Air-2:RenameXtalTest nick$ ls
RM01_03_000_0213_Proj1_Clon1_RC_0000RC000870_010_171222_01_03_02_E0_00_031_001_RAI.jpg
RM01_03_000_0213_Proj1_Clon1_RC_0000RC000870_010_171222_07_07_01_E0_99_031_001_RAI.jpg
rename.py
进入
Nicholass-MacBook-Air-2:RenameXtalTest nick$ ls
RC000870-C1_02-E0_00.jpg
RC000870-G7_01-E0_99.jpg
rename.py
如果看起来像这样,我可以让 rename.py 处理 Python 中的单个名称:
#!/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
但一旦我尝试让脚本在 Unix 中的多个文件上运行 - 它就会失败。这是我对上述内容的脚本尝试:
#!/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
这是我尝试运行它时遇到的错误:
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: ''
谁能帮我理解错误的含义,以及我可以做些什么来修复它?
【问题讨论】:
-
看起来您不处理不是该特定格式的文件名。尝试打印
oldname的值。除了其他文件之外,它可能还会为您提供.、..和rename.py。 -
是的,正如@mooiamaduck 所说。虽然这不是最佳解决方案,但您可以简单地在循环主体中包含类似
if len(oldname) > 70:的 if 语句,以便仅对超过 70 个字符的文件名执行处理。
标签: python dictionary for-loop subprocess substring