Answer the question
In order to leave comments, you need to log in
Is it possible to use open('file','r').read() in python?
The question is perhaps a little silly, but: today, instead of the usual
f = open('file','r')
text = f.read()
f.close()
text = open('file','r').read()
Answer the question
In order to leave comments, you need to log in
You can do this:
In this case, everything will close correctly.
In general, you should try to use modern methods of working with files and paths, rather than prehistoric ones.
By the way, you can make a self-closing reader yourself:
content = pathlib.Path('file').read_bytes()
def readfromfile(filename, mode='t'):
assert mode in {'b', 't'}
with open(filename, mode=mode) as f:
return f.read()
Closes "automatically" only when using the context manager
with open('file','r') as f:
text = f.read()
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question