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?

5
  • 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 Commented Dec 30, 2020 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 How to Ask Commented Dec 30, 2020 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. Commented Dec 30, 2020 at 17:09
  • Does this answer your question? Python program to rename file names while overwriting if there already is that file Commented Dec 30, 2020 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. Commented Dec 30, 2020 at 17:13

1 Answer 1

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 )) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.