Search code examples
python-3.xlistfilesize

How to determine total file sizes from a list of file paths in Python?


I am trying to write a program that tells me the file sizes of all my .png files from my desktop (and every directory under desktop) and tried this:

import os, sys
rootdir = sys.argv[0]
png = []
for root, dirs, files in os.walk('/users/me/desktop'):
    for f in files:
        if os.path.splitext(f)[1] in ['.png']:
            png.append(os.path.join(root,f))
png_list = png
png_sizes = os.path.getsize(png_list)
print(png_sizes)

But I'm getting the following error message:

TypeError: stat: path should be string, bytes, os.PathLike or integer, not list

And am not sure how to fix this. Does anyone have an idea?


Solution

  • os.path.getsize accepts a path, not a list of paths. You can sum the sizes over your list like this:

    png_sizes = sum((os.path.getsize(p) for p in png_list))