Python with Function


Python with keyword creates an unmanaged resource (e.g. stream), executes codes in the block, and then close the resource.

Suppose a text file "tp.txt" with following content:

TTN 27 33 60 54
GATA3 38 20 17 35
HLA-DRB6 18 15 24 27
MUC16 13 15 28 26

The Python script file "test.py" is as follows:
with open("tp.txt") as rad:  #rad is a file object for read
	for line in rad:
		print("line: " + line.rstrip('\n'))

C:\> test.py
line: TTN 27 33 60 54
line: GATA3 38 20 17 35
line: HLA-DRB6 18 15 24 27
line: MUC16 13 15 28 26

Use with to write to file:
>>> with open("tp.txt","w") as writ:
... 	writ.write("Python tutorial")
...
>>> writ.closed #write file stream closed automatically
True