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