Python with statement in IO

In Python you need to give access to a file by opening it.

open() in usual case

If you don’t use with statement, you should write like this:

1
2
3
4
5
6
7
file = open("welcome.txt")

data = file.read()

print data

file.close() # It's important to close the file when you're done with it

file.close() is important, especially in the writing mode. If you don’t close(), the writing action can’t really take effect.

use with in Python IO

1
2
3
4
5
6
7
8
9
10
with open("welcome.txt") as file: # Use file to refer to the file object

data = file.read()

do something with data

# open in write mode
with open('output.txt', 'w') as file: # Use file to refer to the file object

file.write('Hi there!')

Notice, that we didn’t have to write file.close() in the case of using with open() as xx. That will automatically be called.

Reference

  1. With statement in Python : https://www.pythonforbeginners.com/files/with-statement-in-python