Jeff Jeff - 7 months ago 28
Python Question

Rename Files in Python

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.

Answer

Do you want something like this?

$ 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