15

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()
3
  • Just to clarify, the program is loading URLs from the file I'm checking, doing stuff with them, then zeroing out the file using open(URLFile, 'w').close(). I'm going to run the program every few minutes so I want it to exit if no new URLs have been added in the meantime. Commented Jul 19, 2013 at 13:55
  • possible duplicate of python how to check file empty or not Commented Dec 1, 2014 at 14:05
  • Using exceptions for foreseeable and avoidable errors is lazy. Check if the file exists, and if it does, then check its size. Commented Jun 11, 2016 at 1:00

5 Answers 5

18

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"
Sign up to request clarification or add additional context in comments.

4 Comments

This is IMO the best solution.
what about zero byte files?
@shookees -- Forgive my ignorance, but how is a zero byte file different from an empty file?
@TheRogueWolf -- Thanks for catching that. Too early to code apparently :)
2

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

3 Comments

Is FileNotFoundError a thing? (it isn't for me with python2.7 -- That just raises a NameError) For me it's an IOError. Also, I would discourage reading the entire file (what if the user accidentally provides a file which is 8 Gb?) I think you can get the empty/non-empty info from os.stat.
@mgilson: Right; I tested open("blargh") in Python 3 and had expected the exception also to be present in Python 2. So my previous version was actually correct :)
Nice, I hadn't realized that they subclassed IOError and created FileNotFoundError in py3k. cool.
1

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"

1 Comment

I suppose you meant if os.path.exists(path):, otherwise this code is trying to open a file that does not exist.
0

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)

Comments

0

Try this:

if file.tell() == 0:
    print("File is empty!")
else: print("File is not empty")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.