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.
I was originally looking for some GUI which would allow renaming using regular expressions and which had a preview of the result before applying changes.
On Linux I have successfully used krename, on Windows Total Commander does renaming with regexes, but I found no decent free equivalent for OSX, so I ended up writing a python script which works recursively and by default only prints the new file names without making any changes. Add the '-w' switch to actually modify the file names.
Example use case
I want to flip parts of a file name in the following manner, i.e. move the bit
m7-08
to the beginning of the file name:This will perform a dry run, and print the new file names without actually renaming any files:
This will do the actual renaming (you can use either
-w
or--write
):It seems that your problem is more in determining the new file name rather than the rename itself (for which you could use the os.rename method).
It is not clear from your question what the pattern is that you want to be renaming. There is nothing wrong with string manipulation. A regular expression may be what you need here.
What about this :
You can use os.system function for simplicity and to invoke bash to accomplish the task:
Assuming you are already in the directory, and that the "first 8 characters" from your comment hold true always. (Although "CHEESE_" is 7 characters... ? If so, change the 8 below to 7)
The following code should work. It takes every filename in the current directory, if the filename contains the pattern
CHEESE_CHEESE_
then it is renamed. If not nothing is done to the filename.