-3

I did some searches and couldn't find exactly what I needed. I have hundreds of JPG and PDF files in a local directory. All of the file names there have this format:

"Record - LastName, FirstName - EmployeeNum"

I would like to change (re-arrange) the file names to:

"LastName, FirstName - EmployeeNum - Record"

so for example, I'd like the files renamed to something like this: "SMITH, JOE - 1234 - RECORD"

any help would be greatly appreciated.

Thank you!

malikye
  • 19
  • 1
  • 5
  • Use a regular expression with capture groups to extract the parts of the filename. Then use a formatting function to create the new filename, and call `os.rename()`. – Barmar Mar 03 '22 at 19:32
  • @Barmar, I apologize. If you look at my history, you'll see that I've always gave examples of my efforts. In this case, after looking through 5 pages of "changing names with Python" - I couldn't find examples of what I was looking for, and I didn't want to put a lame example out there knowing it's not what I wanted. I will look elsewhere besides StackOverFlow – malikye Mar 03 '22 at 19:41
  • Does [How can I split and parse a string in Python?](https://stackoverflow.com/questions/5749195/how-can-i-split-and-parse-a-string-in-python) answer your question? (hint split on `'-'`) – wwii Mar 03 '22 at 19:42

2 Answers2

1

I'm going to give you some hints to start with:

  • Get all filenames in the desired directory (this can help)
  • For each filename, split it based on - and ,, obtaining 4 strings
  • Rearrange those strings and pass them to os.rename for each original filename to finally rename the files
rikyeah
  • 1,896
  • 4
  • 11
  • 21
0
import os
import glob

for file in glob.glob("*.pdf"):
    record, names, num = file[:-4].split(" - ")
    os.rename(file, f"{names} - {num} - {record}.pdf")

Itay Raveh
  • 161
  • 6
  • this looks great. For JPG files, do I just substitute PDF in the script and run it again? – malikye Mar 03 '22 at 19:43
  • If this is a one-time thing, yes. If this is a task you will perform often, you should have the script operate on both file types. Maybe use regex instead of split(). The snippet I gave is meant to give you a general direction on using the glob and os modules for this task :) – Itay Raveh Mar 03 '22 at 19:48
  • 3
    `.strip(".pdf")` is not the correct way to remove a `.pdf` suffix. It will remove any sequence of `.`, `p`, `d`, or `f` at the beginning or end of the filename. So if the filename is `foo.pdf`, you'll get `oo`. – Barmar Mar 03 '22 at 21:10
  • 1
    Seems I am the luckiest fool on earth, I've avoided error while using a basic function completely wrong. The original answer has been edited, and so will multiple other projects. – Itay Raveh Mar 03 '22 at 21:32