File IO
- mode can be set as the Second parameter of
open
built-in function
default value isread only(r)
r
- read only - file object is created inread only
, file pointer moves to the beginning of the file, Error occurs if the file doesn’t existsw
- write only - creating new file or creating new file object inwrite only
after removing original file’s content, file pointer moves to the beginning of the filea
- addding content at the bottom - creating file object inwrite only
or creating new file if the file doesn’t exist and then putting the file pointer to the end of the file
Binary file mode
rb
wb
ab
It is recommended to close the file object by close()
immediately like f.close()
Using read()
assigns whole content after reading everything
Reading file line by line
Using
for
loof statement1
2
3
4
5
6f = open('t.txt')
i = 1
for line in f:
print i, ":", line,
i += 1
f.close()readline()
- from present file pointer to new line character = A line1
2
3
4
5
6
7
8f = open('t.txt')
line = f.readline()
i = 1
while line:
print i, ":", line,
line = f.readline()
i += 1
f.close()readlines()
- Saving line by line in a list, memory is used inefficiently
It works differently depending on each cases -for in
statement: not reading everything, taking line by line1
2
3
4
5
6
7
8
9
10
11f = open('t.txt')
print f.readlines() # returning a list
# file pointer moves to the beginning of the file
f.seek(0)
i = 1
for line in f.readlines():
print i, ":", line,
i += 1
f.close()xreadlines()
- memory inefficiency improved1
2
3
4
5
6
7
8
9
10
11f = open('t.txt')
print f.xreadlines() # returning file object
# file pointer moves to the beginning of the file
f.seek(0)
i = 1
for line in f.xreadlines():
print i, ":", line,
i += 1
f.close()
for in
or xreadlines()
are recommended
the way to write down line by line
writelines()
- for writing line by line1
2
3
4
5
6
7
8lines = ['1st line\n', '2nd line\n', '3rd line\n']
f = open('t1.txt','w')
f.writelines(lines)
f.close()
f = open('t1.txt')
print f.read() # reading whole content
f.close()write()
- putting\n
between items1
2
3
4
5
6
7
8lines = ['1st line', '2nd line', '3rd line']
f = open('t1.txt','w')
f.write('\n'.join(lines))
f.close()
f = open('t1.txt')
print f.read() # reading whole content
f.close()
Adding content in the existing file existing
- Using mode
a
1
2
3
4
5
6
7f = open('removeme.txt', 'a')
f.write('3rd line\n')
f.close()
f = open('removeme.txt')
print f.read()
f.close()
Seeking specific file pointer
- Sequential access
- specific access
seek(n)
- moving file pointer to the point which is n byte far from the beginning of the filetell()
- returning present file pointer in the file
1 | name = 't.txt' |
sys module’s standard IO(monitor) object
- sys.stdout: standard Input and Output
- sys.stderr: standard error Output
- sys.stdin: standard Input
Saving a file by standard output
1 | import sys |