Skip to content
Advertisement

How to replace characters and rename multiple files?

I have a bunch of pdf files which has the file name as follows:

  1. AuthorA_2014_ This is a good article
  2. BIsanotherAuthor_1994_ Gr8 artcle
  3. CIsFatherOfB_1994_Minor article but not bad

And so on. I would like to change the name of the files to this format:

  1. AuthorA2014This is a good article
  2. BIsanotherAuthor1994Gr8 artcle
  3. CIsFatherOfB1994Minor article but not bad

How do I do this in python? I do have a beginner level knowledge in python. I tried with the code taken from here

import os
path =  os.getcwd()
filenames = os.listdir(path)
for filename in filenames:
    os.rename(filename, filename.replace("_", ""))

With this code I could change the title from AuthorA_2014_ This is a good article to AuthorA2014 This is a good article, which deletes the underscores, but I do not want any empty spaces between the year and title of the article. How do I accomplish this?

I am using Python 3.7.7

Advertisement

Answer

This should get it done:

import os
path =  os.getcwd()
filenames = os.listdir(path)
for filename in filenames:
    os.rename(filename, filename.replace("_", "").replace("_ ", ""))
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement