S
S
Sergo Zar2021-07-01 23:36:56
Python
Sergo Zar, 2021-07-01 23:36:56

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()

I tried it and I was wondering if it is possible to do this and does the file close on its own? Or maybe it's all the same somehow manually close it?
text = open('file','r').read()

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Sergey Pankov, 2021-07-02
@Sergomen

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()

But why, when there is a wonderful pathlib in the third python out of the box?
Well, I’ll also add about the non-closing of files.
In production code that plans to live for a long time, of course, you need to close everything correctly, but if you have a small one-time script that does not open millions of files, then it is quite possible to score on closing it. When the process (interpreter) terminates, all of its handles will be freed.

D
Dmitry Shitskov, 2021-07-02
@Zarom

Closes "automatically" only when using the context manager

with open('file','r') as f:
  text = f.read()

As soon as the code leaves this with block, the file will be closed.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question