Jeff Jeff - 1 year ago 109
Python Question

Rename Files in Python

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

Say I have a file called

and want to remove
so my resulting filename would be

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

Answer Source

Do you want something like this?

$ ls
$ python
>>> import os
>>> for filename in os.listdir("."):
...  if filename.startswith("cheese_"):
...    os.rename(filename, filename[7:])
$ ls
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download