You should check the file size by file and not from a file list.
To check the size of each file in a directory you can use getsize
, that basically returns os.stat(ficheiro).st_size
, and is in bytes
, soon we’ll 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’m dividing by 1024
to get the size in kB although many systems divide by 1000
, I suppose it’s your choice, read more
Similar issue
Thiago, could please edit your question and put the code you’ve already made or a [mcve] ?
– NoobSaibot
import os list = os.Pathlike('c: Users DELL Desktop Python for TP1 networks) size = os.stat(list) print(size.st_size)
– Thiago Cruz