Techython
Techython

Reputation: 1

Size of all images in a list Python/shell

I have a list of images.

Lst = ["1.jpeg", "5.jpeg", "8.jpeg", ....]

I want to know their individual size in Kb/MB. I am using

du - bsh <filename>

But The folder structure is:

Folder/Subfolder1/1.jpeg, 10.jpeg, ... 
Folder/Subfolder2/11.jpeg, 190.jpeg, ...
Folder/Subfolder1/5.jpeg, 90.jpeg, ...
...

Upvotes: 0

Views: 153

Answers (1)

furas
furas

Reputation: 142641

In Python you can get file size using stat()

os.stat(path).st_size

And you can find file(s) using glob.glob with *, ? or **.

files = glob.glob("Folder/*/1.jpeg")

for path in files:
    print(path, os.stat(path).st_size)

It always gives list with all matching paths - even if found only one file or it didn't find any file.

If it may have file in Folder/sub1/sub2/sub3/1.jpeg then you can use ** and recursion

files = glob.glob("Folder/**/1.jpeg", recursive=True)

Of course you can use string formating (.format() or f-string) to search different files from list

for name in Lst:
    files = glob.glob(f"Folder/**/{name}", recursive=True)

Or you can use *.jpeg to get all files and later check if it on the list

files = glob.glob("Folder/**/*.jpeg", recursive=True)

for path in files:
    filename = path.split('/')[-1]
    if filename in Lst:
        print(path, os.stat(path).st_size)        

EDIT:

In Bash you can also use *

for path in Folder/*/*.jpeg 
do 
   du -bsh $path 
done

or in one line

for path in Folder/*/*.jpeg; do du -bsh $path; done

but it still needs to filter files which are on list.

But maybe it could be simpler to use { }

for path in Folder/*/{1,5,8,10,11}.jpeg

For more help in Bash you could ask on similar portals: Unix & Linux or Ask Ubuntu

Upvotes: 1

Related Questions