Python Language Files & Folders I/O Checking if a file is empty

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!


>>> import os
>>> os.stat(path_to_file).st_size == 0


>>> import os    
>>> os.path.getsize(path_to_file) > 0

However, both will throw an exception if the file does not exist. To avoid having to catch such an error, do this:

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

which will return a bool value.

Got any Python Language Question?