'How I can get the size of the all files in python [duplicate]
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
Solution 1:[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.
Solution 2:[2]
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.
Solution 3:[3]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 | Daan Seuntjens |