File IO
Most common operations are file read and write. First, let’s open a file.
Open file
f = open(filename, mode)
filename is filename or path to file. And mode can be read, write or append(‘r’,’w’,’a’). Then f is the file handler.
Close file
Alway remember to close file and free memory.
f.close()
Mode
- “r”: Open a file for read only
- “w”: Open a file for writing. If file already exists its data will be cleared before opening. Otherwise new file will be created
- “a”: Opens a file in append mode i.e to write a data to the end of the file
- “wb”: Open a file to write in binary mode
- “rb”: Open a file to read in binary mode
Write to file
Note that write
will not add \n
automatically, which is default to print
.
f = open('myfile.txt', 'w') # open file for writing
f.write('this is first line\n') # write a line to the file
f.write('this is second line\n') # write one more line
f.close()
Read file
There are three modes:
read([number])
: Return specified number of characters from the file. if omitted it will read the entire contents of the file.readline()
: Return the next line of the file.readlines()
: Read all the lines as a list of strings in the file
Read all file content
f = open('myfile.txt', 'r')
f.read()
'this is first line\nthis is second line\n'
f.close()
Read all lines
f = open('myfile.txt','r')
f.readlines()
['this is first line\n', 'this is second line\n']
f.close()
Read one line
f = open('myfile.txt','r')
f.readline()
'this is first line\n'
f.close()
Append
f = open('myfile.txt','a')
f.write('this is third line\n')
f.close()
Access every line
f = open('myfile.txt','r')
for line in f:
print line,
this is first line
this is second line
this is third line
f.close()
with open
with open('myfile.txt','r') as f:
for line in f:
print line,
this first line
this second line
this is third line
with open('myfile.txt','r') as f:
for line in f.readlines():
print line,
this is first line
this is second line
this is third line