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:
A try
/ except
is indeed the best way.
import os
if os.path.isfile('./file.txt'):
# do something with the file
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.
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