Use os.path.getsize:
>>> import os
>>> os.path.getsize("/path/to/file.mp3")
2071611
The output is in bytes.
Answer from danben on Stack OverflowUse os.path.getsize:
>>> import os
>>> os.path.getsize("/path/to/file.mp3")
2071611
The output is in bytes.
You need the st_size property of the object returned by os.stat. You can get it by either using pathlib (Python 3.4+):
>>> from pathlib import Path
>>> Path('somefile.txt').stat()
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> Path('somefile.txt').stat().st_size
1564
or using os.stat:
>>> import os
>>> os.stat('somefile.txt')
os.stat_result(st_mode=33188, st_ino=6419862, st_dev=16777220, st_nlink=1, st_uid=501, st_gid=20, st_size=1564, st_atime=1584299303, st_mtime=1584299400, st_ctime=1584299400)
>>> os.stat('somefile.txt').st_size
1564
Output is in bytes.
python - File size is zero - Stack Overflow
Loosing my patience and hairs over this - getting size of file returns 0
python - Is it normal that os.stat("file path").st_size returns 0 during the download process? - Stack Overflow
Checking if a file is empty?
When i do it directly ...
>>> import os
size = os.path.getsize('Untitled.rewasd') print(size) 30063
So it works. Now my method ...
def save_config(self,buttons_dict):
self.buttons_dict = buttons_dict
self._generate_jsonfile()
#size = os.path.getsize(self.file_path)
print(self.file_path)
stat = os.stat(self.file_path)
size = stat.st_size
print(size)
# rest is irrelevant
file_exists = os.path.getsize(self.file_path) > 0
f = open(self.file_path, "a+") # open original file
if file_exists: # if file exists and is not empty
self.rewasd_file_bckp_dict = json.load(f)
f_bckp = open(self.file_path + ".bak", "w") # create backup file
f_bckp.write(json.dumps(self.rewasd_file_bckp_dict, indent=4)) # write original content to backup file
f_bckp.close()
f.write(json.dumps(self.rewasd_file_dict, indent=4)) # write new content to backup file
f.close()gives me
python3 main.py
/my/path/to/file/Untitled.rewasd 0
- file size call is above first file opening > https://stackoverflow.com/questions/63091396/os-path-getsize-returns-0
- tried both os.path and os.stat
- all other methods which open file have also .close() for each of them > ful class https://pastebin.com/tyG6Y0yw
Why im still getting this??
I'm trying to determine whether or not a file is empty while iterating through a folder.
def parse_files(results):
for file in results[0]:
with open(file) as my_file:
#if file size is 0, return FalseI feel like the answer is so easy but i've been stuck for a bit.