0

Task: get the size of all images in machine who have extension .png

My not working decision:

import os

file_size = []
for root, dirs, files in os.walk("C:\\"):
    for file in files:
        if file.endswith(".png"):
            file_size.append(os.stat(file).st_size)
print(sum(file_size))

Output:

FileNotFoundError: [WinError 2]

Thoughts:

file_size.append(os.stat(file).st_size)

This code can't find the file to get its attribute, how I can correct this?

thanks

bad_coder
  • 11,289
  • 20
  • 44
  • 72
nox174
  • 1
  • 2

3 Answers3

1

The file holds the relative filenames and os.stat expects its absolute path. You can simply do

file_size.append(os.stat(os.path.join(root, file)).st_size)

You can also use glob module.

0xc0de
  • 8,028
  • 5
  • 49
  • 75
0

Would you be open to using pathlib?

pathlib is a python built-in library just like os and glob.

If a FileNotFoundError is raised for a file having the extension .png, it might not be an actual file, but rather a symlink pointing to the actual file.

In the event that you would like to sum the size of actual .png and avoid accounting for the (negligible) size of symlink that are pointing to .png files, you could detect symlink and avoid any computation based on them. (see below)

from pathlib import Path

ROOT_PATH = Path("C:\\")
_BYTES_TO_MB = 1024 ** 2

img_size_lst = []
img_size_mb_lst = []

for path_object in ROOT_PATH.glob("**/*.png"):
    if path_object.is_symlink():
        continue
    else:
        img_size_lst.append(path_object.stat().st_size)
        img_size_mb_lst.append(path_object.stat().st_size / _BYTES_TO_MB)

print(sum(img_size_lst))

img_size_lst now includes the size, in bytes, of each images.

img_size_mb_lst now includes the size, in mb, of each images.

Alex Fortin
  • 2,105
  • 1
  • 18
  • 27
-1
import glob
import os

png_files = glob.glob("*.png")   # get png files
each_png_file_size = []
for file in png_files:
    each_png_file_size.append(os.stat(png_files[0]).st_size)  # get the size of each file
files_size = sum(each_png_file_size)
print(files_size)  # print total size of all png files in bytes
Daan Seuntjens
  • 880
  • 1
  • 18
  • 37
JafarSadiq
  • 11
  • 1