Home » Python » Python – Check whether a file is empty or not

Python – Check whether a file is empty or not

Posted by: admin January 29, 2018 Leave a comment

Questions:

I have a text file. How can I check whether the file is empty or not empty?

Answers:
>>> import os
>>> os.stat("file").st_size == 0
True

Questions:
Answers:
import os    
os.path.getsize(fullpathhere) > 0

Questions:
Answers:

Both getsize() and stat() will throw an exception if the file does not exist. This function will return True/False without throwing:

import os
def is_non_zero_file(fpath):  
    return os.path.isfile(fpath) and os.path.getsize(fpath) > 0

Questions:
Answers:

if for some reason you already had the file open you could try this:

>>> with open('New Text Document.txt') as my_file:
...     # I already have file open at this point.. now what?
...     my_file.seek(0) #ensure you're at the start of the file..
...     first_char = my_file.read(1) #get the first character
...     if not first_char:
...         print "file is empty" #first character is the empty string..
...     else:
...         my_file.seek(0) #first character wasn't empty, return to start of file.
...         #use file now
...
file is empty

Questions:
Answers:

Ok so I’ll combine ghostdog74’s answer and the comments, just for fun.

>>> import os
>>> os.stat('c:/pagefile.sys').st_size==0
False

False means a non-empty file.

So let’s write a function:

import os

def file_is_empty(path):
    return os.stat(path).st_size==0