python - renaming files with CSV and glob -


i looking make script renames of pdf files have based on .csv file , need match.

the csv file has numbers this:

p20084579 p10092865 p10147356 p20154177 p10028030 p10058367 p10122918 p10122478 p20008810 p10029609 p20015658 

the pdf files named like:

all_c_2017.1.pdf all_c_2017.2.pdf all_c_2017.3.pdf all_c_2017.4.pdf all_c_2017.5.pdf all_c_2017.6.pdf all_c_2017.7.pdf all_c_2017.8.pdf all_c_2017.9.pdf all_c_2017.10.pdf all_c_2017.11.pdf 

etc etc, first number of csv file (p20084579) goes all_c_2017.1.pdf , on, want rename these number p20084579.pdf

i understand how can read in csv files , globs

f =  open('test names.csv', 'rb') reader = csv.reader(f) row in reader:     print row[0]  pdf = glob.glob('*.pdf') pdfname in pdf:     print pdfname  

and hoping os.rename() module have loop be

os.rename(pdfname,row[0]) 

but when use glob list out directories lists rename file incorrectly if try go method:

    all_c_2017.1.pdf     all_c_2017.10.pdf     all_c_2017.11.pdf     all_c_2017.2.pdf     all_c_2017.3.pdf     all_c_2017.4.pdf     all_c_2017.5.pdf     all_c_2017.6.pdf     all_c_2017.7.pdf     all_c_2017.8.pdf     all_c_2017.9.pdf 

any suggestions?

just zip (interleave) both results (from glob.glob , csv.reader) , rename files in loop:

with open('test names.csv', 'r') f:     pdfname,row in zip(glob.glob('*.pdf'),csv.reader(f)):         os.rename(pdfname,row[0]+".pdf") 

notes:

  • it use smart unpacking (new_basename,) directly extract first (and only) row csv file seems exist more columns, forget it.
  • if length of .csv file insufficient, renaming stop. it's better make sure sizes equal. operation may difficult undo.

safe(r) version:

with open('test names.csv', 'r') f:     pdfs = glob.glob('*.pdf')     reader = list(csv.reader(f))     if len(pdfs)!=len(reader):        raise exception("length mismatch")      pdfname,row in zip(pdfs,reader):         os.rename(pdfname,row[0]+".pdf") 

Comments

Popular posts from this blog

python - How to insert QWidgets in the middle of a Layout? -

python - serve multiple gunicorn django instances under nginx ubuntu -

module - Prestashop displayPaymentReturn hook url -