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

Asked

Viewed 2,434 times

1

I’m having a hard time figuring out the size of each file (in KB) in a certain folder. Initially I 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)
  • Thiago, could please edit your question and put the code you’ve already made or a [mcve] ?

  • import os list = os.Pathlike('c: Users DELL Desktop Python for TP1 networks) size = os.stat(list) print(size.st_size)

2 answers

5


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

0

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

The cool thing is that it’s super compact and 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.