Reputation: 353
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()
Upvotes: 15
Views: 37774
Reputation: 1
Try this:
if file.tell() == 0:
print("File is empty!")
else: print("File is not empty")
Upvotes: 0
Reputation: 309929
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"
Upvotes: 18
Reputation: 43495
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)
Upvotes: 0
Reputation: 34698
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"
Upvotes: 1
Reputation: 336158
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()
Upvotes: 2