How can I rename multiple files in a certain directory using Python

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

I'm tried 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. Can someone help??
Nov 23, 2018 in Python by charlie_brown
• 7,780 points
3,396 views

2 answers to this question.

0 votes

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
answered Nov 23, 2018 by aryya
• 7,440 points
0 votes
import os
from optparse import OptionParser, Option

class MyOption (Option):
    ACTIONS = Option.ACTIONS + ("extend",)
    STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
    TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
    ALWAYS_TYPED_ACTIONS = Option.ALWAYS_TYPED_ACTIONS + ("extend",)

    def take_action(self, action, dest, opt, value, values, parser):
        if action == "extend":
            lvalue = value.split(",")
            values.ensure_value(dest, []).extend(lvalue)
        else:
            Option.take_action(
                self, action, dest, opt, value, values, parser)

def parse_opt():

    parser = OptionParser(option_class=MyOption)

    parser.add_option("-r", "--replace", action="extend", type='string', dest='replacename',
                        help = 'type in replace file name here ex: replacing .txt with .py: -r .txt,.py')

    return parser.parse_args()

def filenamechanger():

    # print('Hello World')
    (options, args) = parse_opt()

    # print('hello world')
    ticker = 0
    for filename in os.listdir("."):
        # print(filename)
        if filename.count(str(options.replacename[0])):
            newfilename = str(filename).replace(str(options.replacename[0]),str(options.replacename[1]))
            print('Changing file %s to %s'%(filename,newfilename))
            os.rename(filename, newfilename)
            ticker += 1

    print ("Changed the name of %s files! Nice!"%ticker)

if __name__ == "__main__":

    filenamechanger()

    print ("File Name Changer End...............")
answered Jul 28, 2020 by The real slim shady

Related Questions In Python

0 votes
1 answer

How can I open multiple files using “with open” in Python?

Hello, Just replace and with , and you're done: try: ...READ MORE

answered Nov 20, 2020 in Python by Niroj
• 82,760 points
371 views
0 votes
1 answer

How can I open multiple files using “with open” in Python?

Hello @kartik, Just replace and with , and you're done: try: ...READ MORE

answered Dec 8, 2020 in Python by Niroj
• 82,760 points
104 views
+3 votes
7 answers

How can I rename a file in Python?

yes, you can use "os.rename" for that. ...READ MORE

answered Mar 31, 2018 in Python by DareDev
• 6,890 points
14,424 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,185 views
0 votes
0 answers
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
1,645 views
0 votes
1 answer

How can I rename files on the fly using Python?

You could simply use a wrapper object ...READ MORE

answered Sep 7, 2018 in Python by aryya
• 7,440 points
199 views
0 votes
1 answer

How can I define a multidimensional array in python using ctype?

Here's one quick-and-dirty method: >>> A = ((ctypes.c_float ...READ MORE

answered Oct 9, 2018 in Python by aryya
• 7,440 points
1,887 views