Here is how to check if a text file is empty in Python.


import os 
# Print out 'File is empty!' if nodata.txt is empty
if os.path.getsize('nodata.txt') == 0:
    print("File is empty!") 

Output

If the nodata.txt file would be empty, the output would be:

'File is empty'

If nodata.txt had some content, there will not be any output printed out.


Explanation

You can try this yourself below. The current directory of the embedded Python editor below has two files inside, an empty nodata.txt fileand a non-empty data.txt file. Try changing 'nodata.txt' to 'data.txt' in the code below and run the code. You will get a different output this time.


Related HowTos
Do dictionary comprehension
Do list comprehension
Create a virtual environment
Create a new file
Merge two lists
Extract items from two different lists into one list
Randomly select an item from a list
Generate a random integer
Break a while loop
Create a pandas DataFrame from a dictionary
Create a pandas DataFrame from a list
Get the last item of a list
Delete a column from a pandas dataframe
Access a column of a pandas dataframe
Create a class
Make a webpage request
Get the first two characters of a string
<django.db.models.fields.CharField>
Recommended Course

Learn Flask development and learn to build cool apps with our premium Python course on Udemy.


Mailing List

We will keep you Python-motivated if you subscribe below.