Lesson video

In progress...

Loading...

Hello, my name is Mrs. Holborow, and welcome to Computing.

I'm so pleased you've decided to join me for the lesson today.

In today's lesson, we're going to be learning how to open and read a text file in Python, and then we're going to use iteration to read multiple lines from a text file into our Python programme.

Welcome to today's lesson from the unit, Programming Dictionaries and Data Files.

This lesson is called Reading Text Files.

And by the end of today's lesson, you'll be able to open and read data from a text file in a programme.

Shall we make a start? There are a number of keywords we'll be exploring during today's lesson.

Shall we take a look at them? File.

File, a collection of data stored digitally, identified by a name.

File handling.

File handling, an operation that is specified within a command to open a file that determines how a file can be used.

Strip().

Strip(), a Python method which removes any leading and trailing white spaces or characters that you specify.

Look out for these key words throughout today's lesson.

Today's lesson is broken down into two parts.

We'll start by opening and reading a text file, and then we'll move on to use iteration to read lines from a text file.

Let's make a start by opening and reading a text file.

How would you feel if each time you opened your favourite computer game, it did not open where you had finished the last time you played? Lucas says, "I'd be really frustrated, because it would make me go back to the start each time.

I want the game to open on the level I got to the last time I played it." A file is a term used to describe data that is held in storage on a computer.

Files come in many forms. For example, text files, image files, video files, and sound files.

Files can often be used by other programmes for different purposes.

For example, if you create an image in a painting package, you can then use that same image in a presentation that you've made.

File handling is a term used to describe how programmes work with the files that are stored on a computer.

Having the ability to use file handling techniques in your own programmes opens up endless possibilities.

All of the programmes you've created so far have lost any data generated within them once they have been terminated or closed.

Saving programme to an external file allows you to use that data again.

An example of this might be used to keep track of the highest score for a game.

A text file could be used to store the highest score, and this can be accessed and modified each time the game is played.

Another example is when a programme can be designed to access large data sets.

A weather station can use sensors to take weather readings that are stored in a data file.

A programme can then analyse the data in the file to make predictions about the weather.

The key file-handling techniques that you need to be able to use are open, read, close, write, and depend.

In this lesson, we'll focus on open, read, and close.

In order to read the data stored in a text file, you must open it first.

Think of it a bit like a book.

You can't read what's inside a book unless you open it first.

Here is an instruction that will open a text file in read mode.

So we have file is equal to open, open our brackets, and in speech marks, the name of the file, which in this case is quick.

txt or text, close speech marks, comma, and then in speech marks, we have the letter R, and then we close our bracket.

File creates an identifier for the file that is going to be accessed.

This can be called whatever you want it to be called.

Open calls a function that returns a file object.

The first argument is the name of the text file to be opened.

So in this case, quick.

text.

The second argument is the mode that the file will be opened.

These are some modes for opening a file.

R, for only reading files; W, for only writing to files; and A, for adding to an existing file, 'cause A stands for append.

Jun says, "Be careful.

Opening a file in write mode will erase any existing file with the same name." That's a really good tip, Jun.

We need to be careful.

If we don't want to overwrite data, then we should open a file in read mode.

Time to check your understanding.

Match the file-handling mode to the description.

Pause the video here whilst you have a think.

Did you manage to match the file-handling mode to the description? Well done.

Let's go through the answers.

So R is for reading files, W for writing to files; and A is for adding to an existing file.

Once a file is opened, it can be read.

So you can see we've added a second line of code here, which says "quick.

text = file.

read()." Quick text is a variable that will hold the contents of the text file.

And again, you can name this whatever you want it to be.

File is the identifier for the text file that has been opened, so this needs to be the same as the name that you specified on line one.

So we had file equals open, so in here, we need to have file.

and then the method.

Read is the method that is used to read the contents of the text file.

You must not use the same variable name as the file identifier in your programme.

Time to check your understanding.

What's the problem with this code? Pause the video here whilst you look carefully at the code.

Did you spot the error? The variable name and the file identifier have been called the same thing.

They should be called different names in the programme.

If you want to use text files in the Raspberry Pi Code Editor, you have to add the text file to your project, and you can do that by clicking the blue button, which says Add File on the left hand side of the menu.

You can set the name of the text file, make sure you add the file 'extension.

txt,' which stands for text.

Okay, we're moving on to our first activity of today's lesson, and you've done a fantastic job so far.

So well done.

For task A, I'd like you to open the starter programme at oak.

link/read-file.

Note, this programme already has a text file called quick.

text that you can use so you don't need to create it.

For part two, use the following code to open, read, and display the contents of the text file.

Pause the video here whilst you complete the task.

Once you've opened the starter programme and added the code, test the programme.

The output should look like this.

If it doesn't, maybe go back to step two and check the code.

Okay, so we've opened and read a text file.

We're now going to move on to use iteration to read lines from a text file.

So with this line of code, we have file is equal to open, and we're opening the text file 'quick.

text,' and we're opening it in read mode.

We're then printing the contents of the first line of the file, which gives us the A character.

The read line method can be used to read a single line from a text file.

The method will return the line with a new space character at the end of the string, and this adds a new line.

Each time the readline method is called, the next line in the text file will be returned.

So you can see now we have quick.

But we have a new line in between each one.

Each time the read line method is called, the next line in the text file will be returned.

You can also iterate over a text file using a for loop, and this may be more efficient if you want to read multiple lines.

So here, we have 'for line in file,' and then indented, we have print(line).

What do you think the output will be when this programme is executed? Maybe pause the video here whilst you have a think.

Jun says, "I think it will print each line in the file." I think you are right, Jun.

For every line in the text file, it will print the line along with a line space.

So the output will look similar to this.

Sometimes, we might not want the extra line space after each line.

To remove the extra line space, we can use the strip method.

So you can see here in the print statement, we now have print, open brackets, line.

strip, open bracket, close bracket for the strip method, and then close bracket for the print statement.

Time to check your understanding.

Which method can be used to remove extra line spaces? Is it A, remove(); B, pop(); or C, strip()? Pause the video here whilst you have a think.

That's right, I knew you'd get this right.

The strip method can be used to remove extra line spaces.

Another tool for reading lines is the readlines() method.

You can use this to place each line of the text file as an item in a list.

So you can see here we have quick list is equal to file.

readlines.

And then you can see we have the output, which has put each line from the file in as an item in the list.

The new line character becomes more apparent when you see data in this way.

Note that the new line character is not added to the final line in the text file.

If you want to populate a list with lines from a text file, but you don't want the new line character included in the list, you can write a for loop to populate the list instead.

Let's have a look at this bit of code.

So we have the file.

open, quick.

text in read mode on the first line, we then initialise a list called quicklist and set it as an empty list.

And then we have our for loop.

So for line in file, quicklist.

append, line.

strip, open-close bracket for the strip method, close bracket for the append method.

And then we print the quicklist on the final line of the programme.

So the sample output from this programme will not have the new line characters.

It will just have each line from the file as a list item.

When the data is copied from a text file, it will automatically be held using the string data type.

So you can see this text output has actually put quotation marks around each number, which is probably not very helpful in this case.

To change the data type, you'll need to use casting.

The data should be held as an integer so you can cast it as an integer as you populate the list.

Let's have a look at the amended code.

So we now have, for line in file, numberlist.

append, and then we have open brackets in.

So we're casting it as an integer, open brackets line.

strip for the strip method.

And then we open and close brackets for the strip method.

We close brackets for the int method, and then we close bracket for the append method.

And then we print out the number list.

So now, the text returns the numbers in the list, but without the speech marks around each number.

Note that there are no longer quotes around each number.

Once you have performed all of the tasks that you need to do with a file, it's important to close it.

This will free up system resources and protect the data that is stored in the file.

To close a file, you use the line file.

close, open-close brackets.

Time to check your understanding.

Fill in the gap to complete the sentence.

Once you have performed all of the tasks you need to with a file, it's important to it.

Pause the video whilst you have a think.

That's right.

Did you say close? Once you have performed all of the tasks you need to with a file, it's important to close it.

Okay, we are moving on to our second task of today's lesson, Task B.

I'd like you to open the starter programme, oak.

link/file-numbers.

The text file contains a list of numbers.

You need to create a programme that will read the text file and add each number together before displaying the total sum to the user.

So here's a sample output from the programme.

The total sum of the number is 210.

Pause the video here whilst you complete the activity.

How did you get on? Did you manage to create your programme? Great work.

Let's have a look at some sample code together.

So on line one, we open the file.

File equals open, and then open brackets, numbers.

text, comma, and we're opening this file in read mode.

So we've got the R, and then we've closing our brackets.

On line three, we are initiating a list called numberlist, and we are just initialising that as an empty list.

So we've got empty square brackets.

On line five, we have our for loop, so for line in file, and then on line six, we are reading each line and we're appending it to our list.

So numberlist.

append.

Now, remember, we're dealing with numbers here, so we're gonna cast them as an integer.

So open brackets int, open brackets line.

strip to remove the new line character, open-close brackets for the strip method, close brackets for the int, and then close brackets for the append.

On line eight, we've remembered to close our file once we've finished with it.

So we have file.

close, and then we start with total and our calculation.

So we're initialising a variable called total, and we're setting it to zero.

On line 12, we have four item in number list, and we're looping through, and total is being incremented each time with each item that's stored in the list.

On line 15, we have the final print statement, which says the total sum of the number is, and we're using an F-string here to return the text and the value held by total in the same sentence.

Remember, if you need to make any corrections to your programme, you can pause your video now and do that.

Okay, we've come to the end of today's lesson, Reading Text Files.

You've done a fantastic job, so well done.

Let's summarise what we've learned together.

A file is a term used to describe data that is held in storage on a computer.

File-handling is a term used to describe how programmes work with the files that are stored in a computer.

Different file-handling modes allow you to perform different operations on the contents of a file.

Saving programme data to an external file allows the data to be reused when a programme runs again.

I hope you've enjoyed today's lesson, and I hope you join me again soon.

Bye.