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()
TheRogueWolf
  • 333
  • 1
  • 3
  • 9
  • 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. – TheRogueWolf Jul 19 '13 at 13:55
  • possible duplicate of [python how to check file empty or not](http://stackoverflow.com/questions/2507808/python-how-to-check-file-empty-or-not) – Alex Kulinkovich Dec 01 '14 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. – Richard Haven Jun 11 '16 at 01:00

5 Answers5

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"
TheRogueWolf
  • 333
  • 1
  • 3
  • 9
mgilson
  • 300,191
  • 65
  • 633
  • 696
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()
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
  • 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 Jul 19 '13 at 13:37
  • @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 :) – Tim Pietzcker Jul 19 '13 at 13:39
  • Nice, I hadn't realized that they subclassed IOError and created FileNotFoundError in py3k. cool. – mgilson Jul 19 '13 at 13:43
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"
Jakob Bowyer
  • 33,878
  • 8
  • 76
  • 91
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)
Roland Smith
  • 42,427
  • 3
  • 64
  • 94
0

Try this:

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