In a very small way, you can write your code like this:
from os import path, listdir
pasta = '/diretorio'
lista = [dict(arquivo=f, tamanho=path.getsize(path.join(pasta, f))) for f in listdir(pasta)]
The result will be something like:
[
{'arquivo': 'nota fiscal 08 04 2019.pdf', 'tamanho': 11074},
{'arquivo': 'nota fiscal 08 05 2019.pdf', 'tamanho': 11069},
{'arquivo': 'install.sh', 'tamanho': 1374},
{'arquivo': 'NOTA FISCAL.pdf', 'tamanho': 11028},
{'arquivo': 'test.pdf', 'tamanho': 176427}
]
In the example above, we use a comprehensilist on to generate a list
with a dict
, containing the values arquivo e
size`.
The function path.join
is used with the variable pasta
because the listdir
does not return the full file path, but only its base name inside the folder.
In the tests I did, I used Python version 3.6 and 2.7.
Recursion
If you need to list both directories and subdirectories, I suggest using recursion. I did it this way:
from os import path, walk
pasta = '/home/wallace/Documentos'
def recursive_walk(pasta):
lista = []
for raiz, subdirs, arquivos in walk(pasta):
for f in arquivos:
arquivo = path.join(raiz, f)
lista.append(dict(arquivo=arquivo, tamanho=path.getsize(arquivo)))
for subdir in subdirs:
lista += recursive_walk(subdir)
return lista
lista = recursive_walk(pasta)
print(lista)
Could [Edit] the question add the code you have done so far and describe what was the result obtained? It would also be interesting to add an example folder structure and put what would be the expected result for this example.
– Woss
Related: List files from a Python folder
– Wallace Maxters
Jean, be very careful not to distort your question with the edits. By adding new requests you disable the current answers. If your intention was to generate a spreadsheet with the values, this should be described from the beginning. You’ve seen what it’s like to list the files and their respective sizes, so I think you already have enough material to try to generate the spreadsheet yourself. If you can’t, open a new question.
– Woss