The safest way to open files in Python, whether for reading or writing,
is by using the with
statement:
1 2 | with open('file.txt', 'r') as f:
f.read() # and do some other things...
|
The with
statement ensures that the file's exit code is executed,
closing the file no matter what interruptions may take place. That
prevents files from becoming locked unexpectedly. Some people suggest
embedding the whole with
block in a try-except
block to catch
exceptions.
However, there is one disaster that may befall you even when using
with
. If you open an existing file with a mode of 'w'
(write)
instead of 'r'
(read), the content of the file will be completely
overwritten, even if you do nothing to the file other than open it for
writing. It will have a size of 0 and no content at all.
Since you have probably typed a mode of 'w'
inadvertently, there is no
point recommending the use of other modes as safeties. The safest way to
avoid this problem is to ensure that the file you are reading from is
backed up somewhere. That way, if you type 'w'
instead of 'r'
, you
will still have an easy way to recover.