Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dealing with trying to read a file that might not exist

Tags:

python

What is the best way in python to handle reading a file that may potentially not exist?

Currently I have the following:

    try:
        with open(filename, "r") as f:
            return f.read()
    except IOError:
        return False

Is this the best way to do it or is this wrong on any level at all?

I guess my biggest concerns are:

  1. Catching the exception only to return false
  2. Maybe i am missing a 'Python' way of silently missing the error for a missing file
like image 843
Marty Wallace Avatar asked May 25 '13 17:05

Marty Wallace


3 Answers

A try / except is indeed the best way.

like image 117
Lennart Regebro Avatar answered Oct 24 '22 17:10

Lennart Regebro


import os

if os.path.isfile('./file.txt'):
  # do something with the file
like image 44
imaginabit Avatar answered Oct 24 '22 17:10

imaginabit


A try except block will catch the error, but you might not want to suppress the error.

If you're writing a function that returns the content read from the file, then it would be wiser to return '' instead of False. It's generally a good idea for a function to only return one type. Something like:

try:
    with open(filename) as f:
        return f.read()
except IOError:
    return ''

Really it seems like you're signalling an error condition with a return. If so, you're usually better off just letting the exception propagate out of the function. It's not pythonic to use a returned value to signal an exceptional condition.

like image 43
Ryan Haining Avatar answered Oct 24 '22 16:10

Ryan Haining