简体   繁体   中英

Correct way to check for empty or missing file in Python

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

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"

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM