Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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()
like image 826
TheRogueWolf Avatar asked Jul 19 '13 13:07

TheRogueWolf


People also ask

How can u find out whether the file is empty or not?

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.

How do you check JSON file is empty or not in Python?

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.

How do you check if a line in a text file is empty Python?

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.


3 Answers

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"
like image 86
mgilson Avatar answered Oct 07 '22 12:10

mgilson


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()
like image 2
Tim Pietzcker Avatar answered Oct 07 '22 14:10

Tim Pietzcker


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"
like image 1
Jakob Bowyer Avatar answered Oct 07 '22 13:10

Jakob Bowyer