Skip to content
Advertisement

os.rename() function is causing a FileNotFoundError

I was study the import os today, I working with a rename code.

import os

PictureFolder = "G:VSCodePythonVSWorkPicture"
i = 1
def renameFile():
    for filename in os.listdir(PictureFolder):
        global i
        name, ext = os.path.splitext(filename)
        if ext == ".jpg":
            os.rename(filename, str(f"{i:03}") + ".jpg")
            i += 1
        else:
            print("Processing")

renameFile()

and it was error due to:

FileNotFoundError
[WinError 2] The system cannot find the file specified: 'B.jpg' -> '001.jpg'

So I was confused with the error cause I don’t know what am I doing wrong.

This is the Folder I was working with:

screenshot

Advertisement

Answer

Try this:

import os

PictureFolder = r"G:VSCodePythonVSWorkPicture"
os.chdir(PictureFolder)
i = 1
def renameFile():
    for filename in os.listdir(PictureFolder):
        global i
        name, ext = os.path.splitext(filename)
        if ext == ".jpg":
            os.rename(filename, str(f"{i:03}") + ".jpg")
            i += 1
        else:
            print("Processing")

renameFile()

Edit:

os.chdir(path): Change the current working directory to path.
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement