Jeff Jeff - 2 years ago 133
Python Question

Rename multiple files in a directory 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

Use os.rename(src, dst) to rename or move a file or a directory.

$ 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