简体   繁体   中英

Dealing with trying to read a file that might not exist

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

try / except确实是最好的方法。

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.

import os

if os.path.isfile('./file.txt'):
  # do something with the file

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