This post will cover reading and writing file. We will use built-in function “open()“. Arguments to be used in the open() function
- file
- mode
- encoding – it is important that you specify encoding, otherwise you may get some errors.
import sys
sys.getdefaultencoding()
Example – Write
f = open(‘file.txt’, mode=’wt’, encoding=’utf-8′)
help(f)
f.write(‘this is text I wrote’)
f.write(‘this is the 2nd line \n’)
f.close()
Example – Read
f = open(‘file.txt’, mode=’rt’, encoding=’utf-8′)
f.read(32) # read 32 characters
f.read() # next line
#we should use
f.readline() # to return \n if there are still other lines
f.readlines() # it returns a list of each line