Home > other >  os.rename() function is causing a FileNotFoundError
os.rename() function is causing a FileNotFoundError

Time:02-19

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

import os

PictureFolder = "G:\VSCode\PythonVS\WorkPicture"
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

CodePudding user response:

Try this:

import os

PictureFolder = r"G:\VSCode\PythonVS\WorkPicture"
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.
  • Related