Check the size of each file in a folder in Python with 'os'

1

I'm having a hard time figuring out the size of each file (in KB) in a certain folder. I initially listed all the files with 'os.listdir' and I believe it has something to do with 'os.stat' to find out the size of each file listed.

import os
lista = os.PathLike('c:\Users\DELL\Desktop\Python para redes\TP1')
tamanho = os.stat(lista)
print(tamanho.st_size)
    
asked by anonymous 21.08.2018 / 07:19

2 answers

5

You should check the size of the file to file and not a list of files.

To check the size of each file in a directory you can use getsize , which basically returns os.stat(ficheiro).st_size , and is in bytes , soon we will have to convert:

import os

dir_path = '/caminho/para/ficheiros/'
files = os.listdir(dir_path)
for f in files:
    f_path = os.path.join(dir_path,f)
    f_size = os.path.getsize(f_path)
    f_size_kb = f_size/1024 # obter resultado em kB
    print(f_path, f_size_kb)

If you want to ignore the directories you can ( isfile() ) :

import os

dir_path = '/caminho/para/ficheiros/'
files = os.listdir(dir_path)
for f in files:
    f_path = os.path.join(dir_path,f)
    if(os.path.isfile(f_path)): # verificar se e ficheiro
        f_size = os.path.getsize(f_path)
        f_size_kb = f_size/1024 # obter resultado em kB
        print(f_path, f_size_kb)

Alternative with os.walk , this way you can easily check all files of all directories recursively from a parent directory:

import os

dir_path = '/caminho/para/ficheiros/'
for (dirpath, dirnames, filenames) in os.walk(dir_path): # obtendo caminho atual, diretorios e ficheiros respetivamente
    for f in filenames: # percorrer ficheiros em cada diretorio (dirpath)
        f_path = os.path.join(dirpath, f)
        f_size = os.path.getsize(f_path)
        f_size_kb = f_size/1024 # obter resultado em kB
        print(f_path, f_size_kb)

Note: I am dividing by 1024 to get the size in kB although many systems divide by 1000 , I suppose it is your choice, read more

Similar issue

    
21.08.2018 / 09:12
0

This code takes the sum of all sizes of all files in a folder and all its subfolders (in bytes, if you want kb, just divide by 1024 later).

The cool thing is that it's super compact yet legible:

import os

dir_path = r'c:\Users\DELL\Desktop\Python para redes\TP1'
total = sum(os.path.getsize(os.path.join(path, f)) 
    for path, dirs, files in os.walk(dir_path) for f in files)
    
21.08.2018 / 22:08