Reading from a file - Part 2

In the previous section when we read in data from a file we immediately output it to the screen - obviously this is not something that you will usually do. Normally you will want to make use of the data that you have read into your program. To store it for later use, text be read into a list.

Reading into a list

To read the contents of a file into a list you would need to write the following code:

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

This method reads the entire file and uses the splitlines function to separate the lines of the file and remove the newline character from the end of each line. Once the lines are separated the function places them in a list.

The following video shows you how to read from a file.


Exercises

  1. Write a shopping list in Notepad and save it as 'shopping.txt'. Write a program to read in the shopping list from the file and display it on the screen.
  2. Create a text file in Notepad of user names and passwords. Ask the user to enter their user name and password. The system should read in the details from the file, then return one of these messages:

    • Your login is successful (correct username and password)
    • Incorrect password (username exists but password does not match)
    • This username does not exist (username does not exist in the file)