[英]Batch file renaming – inserting text from a list (in Python or Java)
我正在完成名片制作流程(excel> xml> indesign>單頁pdfs),我想在文件名中插入員工的姓名。
我現在擁有的:
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
當然,你有一張地圖可以看到正確的名稱,你可以在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
是否有意義?
在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
詞典的內容,請告訴我。
如果你有一個以相同順序生成文件的名稱列表,那么在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
蟒蛇:
假設您已經實現了命名邏輯:
for f in os.listdir(<directory>):
try:
os.rename(f, new_name(f.name))
except OSError:
# fail
當然,您需要編寫一個函數new_name
,它接受字符串"BusinessCard_01_Blue.pdf"
並返回字符串"BusinessCard_01_CarlosJorgeSantos_Blue.pdf"
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.