This question already has an answer here:
- How to rename a file using Python 10 answers
- Rename multiple files in Python 2 answers
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.
This sort of stuff is perfectly fitted for IPython, which has shell integration.
Note: to store this in a script, use the
.ipy
extension, and prefix all shell commands with!
.See also: http://ipython.org/ipython-doc/stable/interactive/shell.html
This command will remove the initial "CHEESE_" string from all the files in the current directory, using renamer:
import os import string def rename_files():
rename_files()
Try this:
I'm assuming you don't want to remove the file extension, but you can just do the same split with periods.
Here is a more general solution:
This code can be used to remove any particular character or set of characters recursively from all filenames within a directory and replace them with any other character, set of characters or no character.
I have the same issue, where I want to replace the white space
in any pdf file to a dash
-
. But the files were in multiple sub-directories. So, I had to useos.walk()
. In your case for multiple sub-directories, it could be something like this: