Back

An introduction to reading from a text file - Answers

Q1. Pupils can use their own text files, but it might be a lot easier for the teacher if they all just copy this example to start with. A text file is one that is made up of pure ASCII characters. It might be an idea to ask students to open a Word file and view the hidden characters using the appropriate icon. Ensure students save the file as haiku.txt and that they save it in a folder called Python3 as This is the file that we will be using for the reading and writing examples.
Q2. When you read from and write to text files in Python, you always read and write only strings. If you want to read and write any other kind of data, you need to remember to use something called 'binary mode'. It's best not to get bogged down with a discussion of binary data yet but students do need to understand that they are working purely with strings when reading to and from files at the moment.

To use any file, you must do up to three things ('up to' because if you don't specify them, then common default values are used):

    • firstly create what is called a file object.
    • second, tell Python what you are going to do with the file - it's 'mode'
    • thirdly, tell Python what encoding to use for the characters.

Open a new Python window and copy this program:

poem = open('haiku.txt','r',encoding='utf-8')
print(poem.read())
poem.close()

You must for the moment save it in the same folder as the Haiku poem.

The teacher should run through the different modes. Again, encoding is best left for another day but it is good practise to specify the encoding used.

Q3. Remove this: ,'r',encoding='utf-8' from the first line in your program so it looks like the following:

poem = open('haiku.txt')
print(poem.read())
poem.close()

Defaults are used in Python and students should know what they are.
Q4 - Q5. The teacher should discuss what a full path is and demonstrate how to find the path from a physical device such as a hard drive or USB pen drive, through logical folders to the file that you want to access.

poem = open('haiku.txt','r',encoding='utf-8')
print(poem.read())
poem.close()

Ensure students put the haiku poem back into the same folder as the Python program for the moment.

Q6 - Q10. Practical work repeating what they have learnt so far.

Back