Reading from a file

It is useful to be able to store data in a file so data can be reused later. In Python storing data in text files is very simple. Text files are the sort of files that you can view in Notepad or another text editor. We usually give text files the extension .txt.

Let's start with reading in from a file. To read from a file, you need to first open the file, then use a FOR loop to iterate over each line of the file:

1
2
3
with open("animals.txt", mode="r",encoding="utf-8") as my_file:
    for line in my_file:
        print(line)

Note that we use a with statement to read in the contents of a file. This is the preferred method of opening a file in Python 3 as it ensures that your file is closed properly even if the program throws an exception during execution.

In addition to the filename, open takes two parameters:

  1. mode - this determines what you can do with the file once it has been opened. There are three main options:

    1. w - open the file for writing (this deletes all existing content if the file already exists)
    2. r - open the file for reading
    3. a - open the file to append data to it (preserves existing data in the file)
    4. encoding - this determines the character set that is available when reading from or writing to the file

    5. By default the character encoding is platform dependent. This means that a different character set is used on Windows compared to Mac or Linux.

    6. This not good, therefore we should always set the encoding explicitly as utf-8 when using files.

Newline

One of the issues the you will encounter reading from a file is the newline character. The purpose of the newline character is obvious but it can be annoying as Python adds its own new line character when printing values to the screen. Therefore you should do the following to strip newline characters from a file:

1
2
3
with open("animals.txt", mode="r",encoding="utf-8") as my_file:
    for line in my_file:
        print(line.rstrip("\n"))

Exercise

Practice reading in from a file using method shown above. Make use of the provided animals.txt file.