Reputation: 183
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
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
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