Correct way to check for empty or missing file in Python

Question:

I want to check both whether a file exists and, if it does, if it is empty.

If the file doesn’t exist, I want to exit the program with an error message.

If the file is empty I want to exit with a different error message.

Otherwise I want to continue.

I’ve been reading about using Try: Except: but I’m not sure how to structure the code ‘Pythonically’ to achieve what I’m after?


Thank you for all your responses, I went with the following code:

try:
    if os.stat(URLFilePath + URLFile).st_size > 0:
        print "Processing..."
    else:
        print "Empty URL file ... exiting"
        sys.exit()
except OSError:
    print "URL file missing ... exiting"
    sys.exit()
Asked By: TheRogueWolf

||

Answers:

os.path.exists and other functions in os.path.

As for reading,

you want something like

if not os.path.exists(path):
    with open(path) as fi:
        if not fi.read(3):  #avoid reading entire file.
             print "File is empty"
Answered By: Jakob Bowyer

How about this:

try:
    myfile = open(filename)
except IOError:  # FileNotFoundError in Python 3
    print "File not found: {}".format(filename)
    sys.exit()

contents = myfile.read()
myfile.close()

if not contents:
    print "File is empty!"
    sys.exit()
Answered By: Tim Pietzcker

Try this:

import os
import sys

try:
    s = os.stat(filename)
    if s.st_size == 0:
        print "The file {} is empty".format(filename)
        sys.exit(1)
except OSError as e:
    print e
    sys.exit(2)
Answered By: Roland Smith

I’d use os.stat here:

try:
    if os.stat(filename).st_size > 0:
       print "All good"
    else:
       print "empty file"
except OSError:
    print "No file"
Answered By: mgilson

Try this:

if file.tell() == 0:
    print("File is empty!")
else: print("File is not empty")
Answered By: NiktW
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.