Pushpraj Singh
Pushpraj Singh

Reputation: 21

renaming multiple files using python

I have multiple video files in a directory. Their name contains multiple useless underscores(_).

Ex: How___are_you__doing.

I want to change it to: How are you doing.

I have tried few python codes but couldn't get it right, I am novice programmer.

Upvotes: 0

Views: 71

Answers (3)

Pushpraj Singh
Pushpraj Singh

Reputation: 21

Ok Guys, I finally made it worked. I found this code on GeeksForGeeks, I modified it a little bit to get done what I wanted.

import os
def main():
   path="C:/Users/TP/Desktop/sample/Travel/west bengal/bishnupur/" //paste your dir path here
   for filename in os.listdir(path):
      my_source =path + filename
      my_dest = filename.rename('_',' ')
      my_dest =path + my_dest
      os.rename(my_source, my_dest)
if __name__ == '__main__':
   main()

But It replaced continuous underscores with continuous whitespaces. I am yet to figure out that.

Upvotes: 0

Matthew King
Matthew King

Reputation: 644

An alternative with replace and join:

text = "How___are_you__doing."
text = text.replace("_", " ")
text = ' '.join(text.split())

Output:

How are you doing.

Upvotes: 0

Begoodpy
Begoodpy

Reputation: 1094

What about:

import re
mytitle = "How___are_you__doing."
re.sub("[_]+"," ", mytitle)

Output:

How are you doing.

Upvotes: 1

Related Questions