gfernandes
gfernandes

Reputation: 183

Checking file sizes in python

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

Upvotes: 0

Views: 80

Answers (3)

buran
buran

Reputation: 14233

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.

Upvotes: 1

Matteo Paolucci
Matteo Paolucci

Reputation: 11

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))

Upvotes: 0

user13836714
user13836714

Reputation:

Try this

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

Upvotes: 0

Related Questions