Python open Function


Python file object can open, read and write files.

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

Following Python code can do the same thing (traditional method).
rad = open("tp.txt")
for line in rad:
	print("line: " + line.rstrip('\n'))
rad.close()	


open a file to write:
writ = open("tp.txt","w+")  #writ is a file object for write
writ.write("line 1 content\n")
writ.writelines("line 2 by writeline\n")
writ.writelines("line 3 by writeline\n")
writ.close()

C:\> test.py
line 1 content
line 2 by writeline
line 3 by writeline

open function syntax:
open(file[, mode][, buffer_size])

If no buffer size is specified, no buffering while reading. If buffer_size = 1, line buffering will be performed. If buffer_size > 1, the specified value will be used for buffer size. If buffer_size < 0, the system default will be used as buffer size.

open mode list:
modedescription
rread in text mode
wwrite in text mode, overwrite old file if exists
aappend in text mode
r+read and write
w+read and write, overwrite old file if exists
a+read and append
rbread in binary mode
wbwrite in binary mode, overwrite old file if exists
abappend in binary mode
rb+read and write in binary mode
wb+write and read in binary mode, overwrite old file if exists
ab+append and read in binary mode