How to replace multiple file name in python?

103 Views Asked by At

(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'
>>> 
4

There are 4 best solutions below

0
kindall On BEST ANSWER

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))
0
midori On

You need an absolute path to your file, use join here:

file_path = os.path.join(path, file)
0
Mad Wombat On

You need to switch to the path before you rename or use full names, so either add

os.chdir(path)

somewhere before the loop, or use

os.rename(os.path.join(path, newname), os.path.join(path, file))
1
Sulot On

My error=>

I am not inside the directory. So instead of

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)

It should be:

import os, sys

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

for file in dirs:
    newname=i+file

my error is down there

    os.rename(path+"/"+file, path+"/"+newname)