Rename a batch file - insert text from a list (in Python or Java)

I am completing the business card production flow (excel> xml> indesign> single page pdf files) and I would like to insert the names of the employees in the file names.

What I have now:

BusinessCard_01_Blue.pdf BusinessCard_02_Blue.pdf BusinessCard_03_Blue.pdf (they are gonna go up to the hundreds) 

What I need (I can easily manipulate a list of regular expression names):

 BusinessCard_01_CarlosJorgeSantos_Blue.pdf BusinessCard_02_TaniaMartins_Blue.pdf BusinessCard_03_MarciaLima_Blue.pdf 

I am mom for Java and Python. I read related questions, tried this on Automator (Mac) and Name Mangler, but couldn't get it working.

Thanks in advance, Gus

+4
source share
4 answers

If you have a list of names in the same order as the files, in Python it looks like this unverified snippet:

 #!/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 
0
source

You have a map where you can see the correct name that you could make in Java this way:

 List<Files> originalFiles = ... for( File f : originalFiles ) { f.renameTo( new File( getNameFor( f ) ) ); } 

And define getNameFor something like this:

 public String getNameFor( File f ) { Map<String,String> namesMap = ... return namesMap.get( f.getName() ); } 

On the map you will have associations:

 BusinessCard_01_Blue.pdf => BusinessCard_01_CarlosJorgeSantos_Blue.pdf 

Does it make sense?

+2
source

In Python (verified):

 #!/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)) 

EDIT: now this only modifies files that have not yet been modified.

Let me know if you want something that will automatically create an employees dictionary.

+2
source

Python:

Assuming you have already implemented the naming logic:

 for f in os.listdir(<directory>): try: os.rename(f, new_name(f.name)) except OSError: # fail 

Of course, you will need to write a function new_name , which takes the string "BusinessCard_01_Blue.pdf" and returns the string "BusinessCard_01_CarlosJorgeSantos_Blue.pdf" .

0
source

Source: https://habr.com/ru/post/1340091/


All Articles