-
Notifications
You must be signed in to change notification settings - Fork 0
/
aula172.py
57 lines (45 loc) · 1.97 KB
/
aula172.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# os.path.getsize e os.stat para dados dos arquivos (tamanho em bytes)
import math
import os
from itertools import count
def formata_tamanho(tamanho_em_bytes: int, base: int = 1000) -> str:
"""Formata um tamanho, de bytes para o tamanho apropriado"""
# Original:
# https://stackoverflow.com/questions/5194057/better-way-to-convert-file-sizes-in-python
# Se o tamanho for menor ou igual a 0, 0B.
if tamanho_em_bytes <= 0:
return "0B"
# Tupla com os tamanhos
# 0 1 2 3 4 5
abreviacao_tamanhos = "B", "KB", "MB", "GB", "TB", "PB"
# Logaritmo -> https://brasilescola.uol.com.br/matematica/logaritmo.htm
# math.log vai retornar o logaritmo do tamanho_em_bytes
# com a base (1000 por padrão), isso deve bater
# com o nosso índice na abreviação dos tamanhos
indice_abreviacao_tamanhos = int(math.log(tamanho_em_bytes, base))
# Por quanto nosso tamanho deve ser dividido para
# gerar o tamanho correto.
potencia = base ** indice_abreviacao_tamanhos
# Nosso tamanho final
tamanho_final = tamanho_em_bytes / potencia
# A abreviação que queremos
abreviacao_tamanho = abreviacao_tamanhos[indice_abreviacao_tamanhos]
return f'{tamanho_final:.2f} {abreviacao_tamanho}'
caminho = os.path.join(
'C:/', 'Users', 'danie', 'OneDrive', 'Área de Trabalho',
'vs estudo', 'testes_projetos_python', 'EXEMPLOS AULA 170'
)
counter = count()
for root, dirs, files in os.walk(caminho):
the_counter = next(counter)
print(the_counter, 'Pasta atual', root)
for dir_ in dirs:
print(' ', the_counter, 'Dir:', dir_)
for file_ in files:
caminho_completo_arquivo = os.path.join(root, file_)
stats = os.stat(caminho_completo_arquivo)
tamanho = stats.st_size
print(' ', the_counter, 'FILE:', file_, formata_tamanho(tamanho))
# print(formata_tamanho(1000))
# print(formata_tamanho(1_000_000))
# print(formata_tamanho(1_000_000_000))