批量重命名文件 – 从列表中插入文本(用Python或Java)
我正在完成一个名片制作流程(从 Excel 到 XML,再到 InDesign,最后生成单页 PDF),我想把员工的名字放到文件名里。
我现在有的内容是:
BusinessCard_01_Blue.pdf
BusinessCard_02_Blue.pdf
BusinessCard_03_Blue.pdf (they are gonna go up to the hundreds)
我需要的内容(我可以轻松用正则表达式处理名字列表):
BusinessCard_01_CarlosJorgeSantos_Blue.pdf
BusinessCard_02_TaniaMartins_Blue.pdf
BusinessCard_03_MarciaLima_Blue.pdf
我对 Java 和 Python 还很陌生。我看过相关的问题,尝试在 Automator(Mac)和 Name Mangler 中操作,但都没能成功。
提前谢谢你们,
Gus
4 个回答
2
在Python中(经过测试):
#!/usr/bin/python
import sys, os, shutil, re
try:
pdfpath = sys.argv[1]
except IndexError:
pdfpath = os.curdir
employees = {1:'Bob', 2:'Joe', 3:'Sara'} # emp_id:'name'
files = [f for f in os.listdir(pdfpath) if re.match("BusinessCard_[0-9]+_Blue.pdf", f)]
idnumbers = [int(re.search("[0-9]+", f).group(0)) for f in files]
filenamemap = zip(files, [employees[i] for i in idnumbers])
newfiles = [re.sub('Blue.pdf', e + '_Blue.pdf', f) for f, e in filenamemap]
for old, new in zip(files, newfiles):
shutil.move(os.path.join(pdfpath, old), os.path.join(pdfpath, new))
补充说明:现在这个方法只会改变那些还没有被修改过的文件。
如果你想要一个可以自动生成employees
字典的工具,告诉我哦。
2
假设你有一张地图,可以用来找到正确的名字,你可以在Java中这样做:
List<Files> originalFiles = ...
for( File f : originalFiles ) {
f.renameTo( new File( getNameFor( f ) ) );
}
然后你可以把getNameFor
定义成这样:
public String getNameFor( File f ) {
Map<String,String> namesMap = ...
return namesMap.get( f.getName() );
}
在这张地图里,你会有一些关联:
BusinessCard_01_Blue.pdf => BusinessCard_01_CarlosJorgeSantos_Blue.pdf
这样说清楚了吗?
0
如果你有一个名字的列表,顺序和文件生成的顺序是一样的,在Python中可以这样写,下面是一个未经测试的代码片段:
#!/usr/bin/python
import os
f = open('list.txt', 'r')
for n, name in enumerate(f):
original_name = 'BusinessCard_%02d_Blue.pdf' % (n + 1)
new_name = 'BusinessCard_%02d_%s_Blue.pdf' % (
n, ''.join(name.title().split()))
if os.path.isfile(original_name):
print "Renaming %s to %s" % (original_name, new_name),
os.rename(original_name, new_name)
print "OK!"
else:
print "File %s not found." % original_name