Reputation: 7092
Im tryin to append a short string to every '.png' file. But when I run it, it says cannot find the file. But I know it's there and I can see it in the folder.
Is there anything I need to do?
Here is my script:
import os
for file in os.listdir("./pics"):
if file.endswith(".png"):
newFileName = "{0}_{2}{1}".format(*os.path.splitext(file) + ("z4",))
os.rename(file, newFileName)
Here is the error message I get...02.png is the first file in the folder:
fileNotFoundError: [WinError 2] The system cannot find the file specified: '02.png' -> '02_z4.png'
It's odd though because it gets the filename, in this case, 02.png
. So if it can read the file name, why can't it find it?
Thanks!
Upvotes: 1
Views: 881
Reputation: 611
The name returned from os.listdir() gives the filename, not the full path. So you need to rename pics/02.png to pics/02_zf.png. Right now you don't include the directory name.
Upvotes: 1
Reputation: 7233
I thought my comment might be enough, but for clarity I'll provide a short answer.
02.png
doesn't exist relative to your working directory. You need to specify the path to the file for os.rename
so you need to include the directory.
import os
for file in os.listdir("./pics"):
if file.endswith(".png"):
newFileName = "/pics/{0}_{2}{1}".format(*os.path.splitext(file) + ("z4",)) # Notice the ./pics
os.rename(os.path.join('pics', file), newFileName)
Upvotes: 1