How to check whether a file is empty or not

PythonFileFile Length

Python Problem Overview


I have a text file. How can I check whether it's empty or not?

Python Solutions


Solution 1 - Python

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

Solution 2 - Python

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

Solution 3 - Python

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

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

Solution 4 - Python

If you are using Python 3 with pathlib you can access os.stat() information using the Path.stat() method, which has the attribute st_size (file size in bytes):

>>> from pathlib import Path
>>> mypath = Path("path/to/my/file")
>>> mypath.stat().st_size == 0 # True if empty

Solution 5 - Python

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" # The first character is the empty string..
...     else:
...         my_file.seek(0) # The first character wasn't empty. Return to the start of the file.
...         # Use file now
...
file is empty

Solution 6 - Python

if you have the file object, then

>>> import os
>>> with open('new_file.txt') as my_file:
...     my_file.seek(0, os.SEEK_END) # go to end of file
...     if my_file.tell(): # if current position is truish (i.e != 0)
...         my_file.seek(0) # rewind the file for later use 
...     else:
...         print "file is empty"
... 
file is empty

Solution 7 - Python

Combining ghostdog74's answer and the comments:

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

Solution 8 - Python

Since you have not defined what an empty file is: Some might also consider a file with just blank lines as an empty file. So if you want to check if your file contains only blank lines (any white space character, '\r', '\n', '\t'), you can follow the example below:

Python 3

import re

def whitespace_only(file):
    content = open(file, 'r').read()
    if re.search(r'^\s*$', content):
        return True

Explanation: the example above uses a regular expression (regex) to match the content (content) of the file.

Specifically: for a regex of: ^\s*$ as a whole means if the file contains only blank lines and/or blank spaces.

  • ^ asserts position at start of a line
  • \s matches any white space character (equal to [\r\n\t\f\v ])
  • * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
  • $ asserts position at the end of a line

Solution 9 - Python

An important gotcha: a compressed empty file will appear to be non-zero when tested with getsize() or stat() functions:

$ python
>>> import os
>>> os.path.getsize('empty-file.txt.gz')
35
>>> os.stat("empty-file.txt.gz").st_size == 0
False

$ gzip -cd empty-file.txt.gz | wc
0 0 0

So you should check whether the file to be tested is compressed (e.g. examine the filename suffix) and if so, either bail or uncompress it to a temporary location, test the uncompressed file, and then delete it when done.

Better way to test size of compressed files: read it directly using the appropriate compression module. You would only need to read the first line of the file, for example.

Solution 10 - Python

If you want to check if a CSV file is empty or not, try this:

with open('file.csv', 'a', newline='') as f:
    csv_writer = DictWriter(f, fieldnames = ['user_name', 'user_age', 'user_email', 'user_gender', 'user_type', 'user_check'])
    if os.stat('file.csv').st_size > 0:
        pass
    else:
        csv_writer.writeheader()

Solution 11 - Python

A Complete Example For Appending JSON To A File

Reusable Function

import json
import os 

def append_json_to_file(filename, new_data):
    """ If filename does not exist """
    data = []
    if not os.path.isfile(filename):
        data.append(new_data)
        with open(filename, 'w') as f:
            f.write(json.dumps(data))
    else:
        """ If filename exists but empty """
        if os.stat(filename).st_size == 0:
            data = []
            with open(filename, 'w') as f:
                f.write(json.dumps(data))
        """ If filename exists """
        with open(filename, 'r+') as f:
            file_data = json.load(f)
            file_data.append(new_data)
            f.seek(0)
            json.dump(file_data, f)

Run It

filename = './exceptions.json'
append_json_to_file(filename, {
    'name': 'LVA',
    'age': 22
})
append_json_to_file(filename, {
    'name': 'CSD',
    'age': 20
})        

Result

[{"name": "LVA", "age": 22}, {"name": "CSD", "age": 20}]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionwebminal.orgView Question on Stackoverflow
Solution 1 - Pythonghostdog74View Answer on Stackoverflow
Solution 2 - PythonJonView Answer on Stackoverflow
Solution 3 - PythonronedgView Answer on Stackoverflow
Solution 4 - PythonM.TView Answer on Stackoverflow
Solution 5 - Pythonrobert kingView Answer on Stackoverflow
Solution 6 - PythonQlimaxView Answer on Stackoverflow
Solution 7 - PythonRon KleinView Answer on Stackoverflow
Solution 8 - PythonKV88View Answer on Stackoverflow
Solution 9 - PythonTrutaneView Answer on Stackoverflow
Solution 10 - PythonRajan SinghView Answer on Stackoverflow
Solution 11 - PythonSean WilliamView Answer on Stackoverflow