mchd
mchd

Reputation: 3163

FileNotFoundError when trying to rename all the files in a directory

I am writing a python script to rename all files in a given folder. The python script exists in my j-l-classifier along with images/jaguar file. I'm trying to run the following script to take each file in the folder and rename it to this format:

jaguar_[#].jpg

But its throwing the following error:

Traceback (most recent call last):
  File "/home/onur/jaguar-leopard-classifier/file.py", line 14, in <module>
    main()
  File "/home/onur/jaguar-leopard-classifier/file.py", line 9, in main
    os.rename(filename, "Jaguar_" + str(x) + file_ext)
FileNotFoundError: [Errno 2] No such file or directory: '406.Black+Leopard+Best+Shot.jpg' -> 'Jaguar_0.jpg'

This is my code:

import os


def main():
    x = 0
    file_ext = ".jpg"

    for filename in os.listdir("images/jaguar"):
        os.rename(filename, "Jaguar_" + str(x) + file_ext)
        x += 1


if __name__ == '__main__':
    main()

Upvotes: 1

Views: 419

Answers (2)

hifromdev
hifromdev

Reputation: 262

In order to use os.rename(), you need to provide absolute paths.

I would suggest replacing line 9 with os.rename(os.path.expanduser(f"~/{whatever folders you have here}/images/jaguar/{filename}"), os.path.expanduser(f"~/{whatever folders you have here}/images/jaguar/Jaguar_{str(x)}{file_ext}")

os.path.expanduser() allows you to use the "~" syntax to aid the abs file path.

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 113940

os.listdir only returns the filename (not the file path...)

try the following

for filename in os.listdir("images/jaguar"):
    filepath = os.path.join("images/jaguar",filename)
    new_filepath = os.path.join("images/jaguar","Jaguar_{0}{1}".format(x,file_ext))
    os.rename(filepath, new_filepath)

being explicit is almost always a path to a happier life

Upvotes: 1

Related Questions