Reputation: 514
(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'
>>>
Upvotes: 0
Views: 109
Reputation: 514
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
os.rename(path+"/"+file, path+"/"+newname)
Upvotes: 1
Reputation: 184081
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))
Upvotes: 3
Reputation: 15105
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))
Upvotes: 2
Reputation: 4837
You need an absolute path to your file, use join here:
file_path = os.path.join(path, file)
Upvotes: 1