Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python read/write file without closing

Tags:

python

file

Sometimes when I open a file for reading or writing in Python

f = open('workfile', 'r')

or

f = open('workfile', 'w')

I read/write the file, and then at the end I forget to do f.close(). Is there a way to automatically close after all the reading/writing is done, or after the code finishes processing?

like image 240
Mika H. Avatar asked Jan 24 '26 01:01

Mika H.


2 Answers

with open('file.txt','r') as f:
    #file is opened and accessible via f 
    pass
#file will be closed before here 
like image 129
HennyH Avatar answered Jan 25 '26 16:01

HennyH


You could always use the with...as statement

with open('workfile') as f:
    """Do something with file"""

or you could also use a try...finally block

f = open('workfile', 'r')
try:
    """Do something with file"""
finally:
    f.close()

Although since you say that you forget to add f.close(), I guess the with...as statement will be the best for you and given it's simplicity, it's hard to see the reason for not using it!

like image 31
msegf Avatar answered Jan 25 '26 15:01

msegf



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!