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()
Check if the File is Empty using os.getsize() to check whether a file is empty or not. It takes the file path as an argument. It will check for the file size. If the file size is 0, it will print the file as Empty.
path. getsize(path) to find file size of a file. You do not have to read file at all. If JSON file is just 2 bytes, "[]" or "{}", it is an empty JSON object.
Using len() function To check an empty string in Python, use the len() function; if it returns 0, that means the string is empty; otherwise, it is not. So, if the string has something, it will count as a non-empty string; otherwise, it is an empty string.
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"
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()
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With