Home > Mobile >  FileNotFoundError when sorting files by size
FileNotFoundError when sorting files by size

Time:09-26

I am trying create a list of image file names, sorted by the size of the file:

path = '/home/onur/Desktop/dataset/'

images = sorted(os.listdir(path), key = os.path.getsize)
print(images)

But I'm getting this error:

Traceback (most recent call last):
  File "/home/onur/Desktop/image-downloader.py", line 98, in <module>
    images = sorted(os.listdir(path), key = os.path.getsize)
  File "/usr/lib/python3.9/genericpath.py", line 50, in getsize
    return os.stat(filename).st_size
FileNotFoundError: [Errno 2] No such file or directory: 'image_535.jpg'

The python file is NOT in /home/onur/Desktop/dataset/. It is just in Desktop so I wonder if that is the reason for the error. If so, how can I fix it?

CodePudding user response:

You are correct. The problem is that os.path.getsize raises an error if the file does not exist. Because your Python script is in /home/onur/Desktop and the file name passed to os.path.getsize is just image_535.jpg, os.path.getsize looks for the file in your Desktop directory. Since the file is not there, os.path.getsize raises the error. You could run this to correctly test the file size.

path = '/home/onur/Desktop/dataset/'

images = sorted(os.listdir(path), key=lambda f: os.path.getsize(os.path.join(path, f)))

print(images)
  • Related