Part 9 Python Files and Resource Management

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

Example – Write
f = open(‘file.txt’, mode=’wt’, encoding=’utf-8′)
f.write(‘this is text I wrote’)
f.write(‘this is the 2nd line \n’)

Example – Read
f = open(‘file.txt’, mode=’rt’, encoding=’utf-8′) # read 32 characters # 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

Leave a Reply

Your email address will not be published. Required fields are marked *