0

I'm trying to check the file size of a bunch of files from a specific directory, but not being able, could you guys help me?

import os
dir_path = 'C:\\temp\\cmm_temp\\tmp\\'
files = os.listdir(dir_path)
with open(dir_path+files, "r") as arq:
    for arq in files:
        file_size = os.stat(str(arq)).st_size
        if file_size == 0:
            print("The file  is empty: "+str(arq) + str(file_size))
        else:
            print("The file is not empty: " +str(arq) + str(file_size))

that's the output

C:\USER_ATU\PycharmProjects\CMM_SDL157\venv\Scripts\python.exe C:/USER_ATU/PycharmProjects/CMM_SDL157/venv/Scripts/testFile.py
Traceback (most recent call last):
  File "C:/USER_ATU/PycharmProjects/CMM_SDL157/venv/Scripts/testFile.py", line 35, in <module>
    with open(dir_path+files, "r") as arq:
FileNotFoundError: [Errno 2] No such file or directory: "C:\\temp\\cmm_temp\\tmp\\['MST_DatFileList.txt', 'MST_TtsFileParsed.txt', 'test_fileZero.txt', 'ZTN_DatFileList.txt', 'ZTN_TtsFileParsed.txt']"

Process finished with exit code 1

Thanks

gfernandes
  • 193
  • 1
  • 10
  • You need to search well. Too many ways to do: [https://stackoverflow.com/questions/2104080/how-can-i-check-file-size-in-python](https://stackoverflow.com/questions/2104080/how-can-i-check-file-size-in-python) – Dartagnan Mar 30 '21 at 07:03

3 Answers3

1

files is a list. You need to iterate over it and pass single file to os.stat. I simplified your code a bit:

import os
dir_path = 'C:\\temp\\cmm_temp\\tmp\\'
for fname in os.listdir(dir_path):
    full_path = os.path.abspath(os.path.join(dir_path, fname))
    file_size = os.stat(full_path).st_size
    print(f"The file{' not ' if file_size else ' '}is empty: {full_path}, {file_size}")

Note, os.listdir will yield both files and folders and thus the code will print size of both files and folders.

buran
  • 13,682
  • 10
  • 36
  • 61
  • Thanks for you reply, it worked, but I trying to add an exception to my for, when I got 2 files empty it breaks and return the exception, something like this: dir_path = 'C:\\temp\\cmm_temp\\tmp\\' totFilesEmpty = 0 for fname in os.listdir(dir_path): try: full_path = os.path.abspath(os.path.join(dir_path, fname)) file_size = os.stat(full_path).st_size if file_size == 0: totFilesEmpty = totFilesEmpty + 1 except Exception as ab: print("number of empty files == 02", ab) but, it's not going to the Exception, any ideas why? – gfernandes Mar 30 '21 at 12:29
  • just to be clear, I need to check if the files from a folder are empty, if I have 2 empty files, I want to break my code and return an Exception, sorry, but I'm new to python, so I might be missing something – gfernandes Mar 30 '21 at 12:34
0

Try this

import os
b = os.path.getsize("__path__")
print(b) 

0

You could simply check if the file is a regular file and then use os.path.getsize()
Example:

import os

files = os.listdir(_)
for file in files:
    if os.path.isfile(file):
        print(file, os.path.getsize(file))