Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rename multiple files in a directory in Python [duplicate]

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.

like image 901
Jeff Avatar asked May 03 '10 15:05

Jeff


People also ask

How do I batch rename multiple files at once?

You can press and hold the Ctrl key and then click each file to rename. Or you can choose the first file, press and hold the Shift key, and then click the last file to select a group.

How do I automatically rename multiple files?

To batch rename files, just select all the files you want to rename, press F2 (alternatively, right-click and select rename), then enter the name you want on the first file. Press Enter to change the names for all other selected files.


2 Answers

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

$ 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 
like image 84
Messa Avatar answered Oct 17 '22 11:10

Messa


Here's a script based on your newest comment.

#!/usr/bin/env python from os import rename, listdir  badprefix = "cheese_" fnames = listdir('.')  for fname in fnames:     if fname.startswith(badprefix*2):         rename(fname, fname.replace(badprefix, '', 1)) 
like image 45
bukzor Avatar answered Oct 17 '22 13:10

bukzor