0%

open() VS with open() in Python

To open a file object in read mode, you need to use Python’s built-in open() function and pass in the filename and identifier:

1
>>> f = open('test.txt', 'r')

open()

The identifier 'r' indicates read, so we successfully opened a file.

If the file does not exist, the open() function will throw an IOError error:

1
2
3
4
5
6
>>> f = open('notfound.txt', 'r')
... f.read()
... f.close()
Traceback (most recent call last):
  File "", line 1, in
FileNotFoundError: [Errno 2] No such file or directory: 'notfound.txt'

😰 The final step is to call the close() method to close the file. Files must be closed after they are used, because file objects take up resources from the operating system. The number of files that the system can open at the same time is limited.

try … finally

Since the file may throw an IOError while reading or writing. Once an error occurs, the following f.close() will not be called. So, in order to ensure that the file can be closed, we can use try ... finally to achieve: 🙉

1
2
3
4
5
6
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()

with open()

But it’s too cumbersome to write this every time, so Python introduces a with statement to automatically call the close() method for us: 😍

1
2
with open('/path/to/file', 'r') as f:
print(f.read())

This is the same as the previous try ... finally, but the code is better and cleaner, and you don’t have to call the f.close() method.