Skip to main content

10.3) File Reading: Some Explanations


Let’s analyse the process line by line. You open a file with:

f=open(file,mode)

file is a string with the path (address) and name of the file. mode is optional, it allows you to protect a file that you wouldn’t want to change or that you only want to add to rather than overwrite. There are several other modes of opening a file:

  • 'r' the file will only be read
  • 'w' for only writing (an existing file with the same name will be erased)
  • 'a' opens the file for appending; any data written to the file is automatically added to the end
  • 'r+' opens the file for both reading and writing

The function open() returns a file object value, here called f. It’s like an address or identification for the file.

You can then read the content of a file with several file methods read() readlines() and readline(). For example:

content=f.read()

This will return a string with all the content of the file.

lines=f.readlines()

This will return a list of strings corresponding to all the individual lines in the file.

line=f.readline()

This will return a string with one line and advances to the next line so you can simply read the next line with:

line2=f.readline()