Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (47.6k points)

I'm trying to rename some files in a directory using Python.

Say I have a file called CHEESE_CHEESE_TYPE.*** and want to remove CHEESE_ so my resulting filename would be CHEESE_TYPE

I'm trying to use the os.path.split but it's not working properly. I have also considered using string manipulations, but have not been successful with that either.

1 Answer

0 votes
by (106k points)

To rename multiple files in a directory in Python you can use os.rename(src, dst) to rename or move a file or a directory.

$ ls 

cheese_cheese_type.bar cheese_cheese_type.foo 

$ python 

>>> import os 

>>> for filename in os.listdir("."): 

... if filename.startswith("cheese_"): 

... os.rename(filename, filename[7:]) 

... 

>>> 

$ ls 

cheese_type.bar cheese_type.foo

To know more about this you can have a look at the following video tutorial:-

Related questions

+2 votes
3 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...