Search code examples
pythonpython-3.xdir

How to replace multiple file name in python?


(ANSWERED) I want to change file name from this directory. Let call them ai01.aif, ab01.aif to changedai01.aif, changedab01.aif.

import os, sys

path="/Users/Stephane/Desktop/AudioFiles"
dirs=os.listdir(os.path.expanduser(path))
i="changed"

for file in dirs:
    newname=i+file
    os.rename(file,newname)

I got this error:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'ai01.aif' -> 'changedai01.aif'
>>> 

Solution

  • There is no file named ai01.aif in the current directory (this is often the one your script is in, but might be elsewhere). The directory you got the content of is not the current directory. You will need to add the directory you're working in to the beginning of the filenames.

    import os, sys
    
    path = os.path.expanduser("/Users/Stephane/Desktop/AudioFiles")
    dirs = os.listdir(path)
    i    = "changed"
    
    for file in dirs:
        newname = i + file
        os.rename(os.path.join(path, file), os.path.join(path, newname))