3

I am studying Python and I found there are two types of file opening operations. The first one is,

myreadfile = open("bear.txt", "r")
content = myreadfile.read()

second method is

with open("bear.txt") as file:
    content = file.read()

I want to know is there any difference between these two methods and which one is most suitable to use.

Haree.H
  • 53
  • 7
  • The with statement is called the context manager. It handles closing the file automatically for you. – Isotope Jul 16 '21 at 05:45
  • Does this answer your question? [What is the python "with" statement designed for?](https://stackoverflow.com/questions/3012488/what-is-the-python-with-statement-designed-for) – Lomtrur Jul 16 '21 at 05:58

5 Answers5

5

They are context managers.

Explanation:

The with method is a context manager, if you use it for reading or writing I/O files, it will automatically close the file, don't need to add a line of file.close(), as mentioned in the docs:

Context managers allow you to allocate and release resources precisely when you want to. The most widely used example of context managers is the with statement. Suppose you have two related operations which you’d like to execute as a pair, with a block of code in between. Context managers allow you to do specifically that.

Examples:

There are examples in the docs, a regular with statement:

with open('some_file', 'w') as opened_file:
    opened_file.write('Hola!')

Is equivalent to:

file = open('some_file', 'w')
try:
    file.write('Hola!')
finally:
    file.close()

It says that:

While comparing it to the first example we can see that a lot of boilerplate code is eliminated just by using with. The main advantage of using a with statement is that it makes sure our file is closed without paying attention to how the nested block exits.

A brief introduction of the implementation:

As mentioned in the docs, the context manager could be implemented with a class:

At the very least a context manager has an __enter__ and __exit__ method defined.

As shown there, an example context manager implementation in a class would be something like:

class File(object):
    def __init__(self, file_name, method):
        self.file_obj = open(file_name, method)
    def __enter__(self):
        return self.file_obj
    def __exit__(self, type, value, traceback):
        self.file_obj.close()
with File('demo.txt', 'w') as opened_file:
    opened_file.write('Hola!')

The code can behave like a context manager due to the magic methods, __enter__ and __exit__.

U13-Forward
  • 69,221
  • 14
  • 89
  • 114
0

The first one does not close the file automatically. The second one does.

marckesin
  • 71
  • 4
0

As far as I understand, the first one, you need to close the file after you're done with the operations while in the latter the file is automatically closed after execution of that indent block.

0

The second method is the recommended method. This with syntax is known as a context and will automatically close the file once the context is exited as well as if something goes wrong during the operation.

chthonicdaemon
  • 19,180
  • 2
  • 52
  • 66
0

In the first case, the file is opened and read. It stays open afterwards.

In the second case, you use the file object as a so-called "context manager". Special methods get called on entering and leaving the with block: on leaving, it is closed. This is superior to the other, even superior to

myreadfile = open("bear.txt", "r")
content = myreadfile.read()
myreadfile.close()

because the close() line isn't reached when read() throws an exception.

It is more like

myreadfile = open("bear.txt", "r")
try:
    content = myreadfile.read()
finally:
    myreadfile.close()

but easier to use.

glglgl
  • 89,107
  • 13
  • 149
  • 217