0

I need to change file names inside a folder

My file names are

BX-002-001.pdf
DX-001-002.pdf
GH-004-004.pdf
HJ-003-007.pdf

I need to add an additional zero after '-' at the end, like this

BX-002-0001.pdf
DX-001-0002.pdf
GH-004-0004.pdf
HJ-003-0007.pdf

I tried this

all_files = glob.glob("*.pdf")
for i in all_files:
    fname = os.path.splitext(os.path.basename(i))[0]
    fname = fname.replace("-00","-000")

My code is not working, can anyone help?

sebin
  • 63
  • 3
  • 1
    You are modifying the variable containing your filename as a string, but you are not renaming the file. Is this answer helpful to you? [Python program to rename file names while overwriting if there already is that file](https://stackoverflow.com/questions/30175369/python-program-to-rename-file-names-while-overwriting-if-there-already-is-that-f) – Moinuddin Quadri Dec 30 '20 at 17:04
  • What do you mean "not working"? Does it fail to rename the file? Does it rename it wrongly? Does it cause your computer to explode? "My code doesn't work, fix it for me" is off-topic here. You must ask a _specific_ question. Please take the [tour] and read [ask] – Pranav Hosangadi Dec 30 '20 at 17:06
  • @PranavHosangadi I think it is obvious enough that the files are not beeing renamed, and the fix is also obvious enough to write an answer. So no harm done. – wuerfelfreak Dec 30 '20 at 17:09
  • Does this answer your question? [Python program to rename file names while overwriting if there already is that file](https://stackoverflow.com/questions/30175369/python-program-to-rename-file-names-while-overwriting-if-there-already-is-that-f) – Pranav Hosangadi Dec 30 '20 at 17:10
  • @wuerfelfreak whether or not it is obvious, "my code doesn't work" must include a description of how it is supposed to work and what it actually does. OP is supposed to provide as much relevant information as possible to the people volunteering their time here. – Pranav Hosangadi Dec 30 '20 at 17:13

1 Answers1

2

fname = fname.replace("-00","-000") only changes the variable fname in your program. It does not change the filename on your disk.

you can use os.rename() to actully apply the changes to your files:

all_files = glob.glob("*.pdf")
for i in all_files:
    fname = os.path.splitext(os.path.basename(i))[0]
    fname = fname.replace("-00","-000")
    os.rename(i, os.path.join(os.path.dirname(i), fname ))
wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29