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 write new text to a file.
We'll also see how to append text to an existing file.
Welcome to today's lesson from the unit "Programming dictionaries and data files".
This lesson is called "Writing to a text file", and by the end of today's lesson, you'll be able to write data to a new file and append data to an existing text file.
Shall we make a start? We will be exploring these keywords throughout today's lesson.
Write.
Write.
A file handling mode that allows a programme to write data to a file, where if the file does not exist, a new file is created.
And if the file already exists, the content is overwritten.
Append.
Append.
A file handling mode that allows a programme to write extra data at the end of a file without erasing the existing contents of the file.
Overwrite.
Overwrite.
To replace information in a computer file with new information.
Look out for these keywords throughout today's lesson.
Today's lesson is broken down into two parts.
We'll start by writing to a new text file.
We'll then move on to append text to an existing file.
Let's make a start and write to a new text file.
The key file handling techniques that you need to be able to use are open, read, close, write, and append.
In today's lesson, we're going to be looking at write and append.
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, because A stands for "append".
Here is an instruction that will open a text file in write mode.
So we have file is equal to open, open our brackets.
In speech marks we have the name of the file, which is "players.
txt", and then we have comma, and then in speech marks we have W, which stands for write mode.
And then we close our bracket.
When you open a file name in write mode, it creates a new file with the specified file name.
Time to check your understanding.
What would you add in the gap to write to the file players.
txt? Is it A, R? B, A? Or C, W? Pause the video whilst you have a think.
Did you select C, W? Well done.
We want to be able to write to the file, so we need to open it in the write mode.
When you open a file in write mode, it creates a new file with the specified file name.
So in this example, players dot text, or TXT.
Jun says, "Be careful.
If that file already exists, then the file will be overwritten." So you need to be really careful with your file names here, and be aware of what files you already have saved on your system.
Watch this video to see how to write to a file.
Okay, we're gonna do some live coding now to see how we create a new file and write some contents to the file.
So I've opened the Raspberry Pi code editor, and I have copied across exactly the same line that we have seen in the slide deck.
So we've got file is equal to open, open brackets, and then we have the name of the file, which is players.
txt.
And then a comma.
And then we have W, which is the file handling method which we are using which is the write method in this case.
So we're saying open the file called players.
txt.
And if it's not created already, then it will create that file, and we're going to write some new contents to it.
Now, if I hit "run" in the Raspberry Pi code editor, nothing will happen here.
If you are using a different IDE, for example, you may have an IDE installed directly on your machine, you may find that when you hit "run" with this line of code, that actually the text file, players.
txt, is created, and it just creates a blank file at this point.
In the Raspberry Pi code editor, the file won't be created until we write something to it.
So that behaves perhaps slightly differently to some other IDEs.
So what I'm going to do is I'm going to add a new line of code this time, and I'm going to write file.
write, and I am going to add the name of the first player in speech marks, which is going to be Aisha.
Okay? Now it's always good practise to do a file.
close, and in some IDE environments, if you don't write the line file.
close, then you'll find that actually, the text isn't written to the file.
So it's important to add that in.
So if I hit run now, hopefully we will see that in our project files on the left hand side, we have a text file which has been created, which is called "players".
And if I click on that text file to open it, we can see that the name Aisha has been written to the file.
Now if I go back to my code, and I change Aisha's name to Jun, and I run the code again, if we go back to players.
txt, we can see that, because we're using the write mode that the original name that we added which was Aisha has been overwritten, and we now have the name Jun in the file instead.
So we have to be careful when we're using the write mode because it will overwrite the original contents of the file.
Time to check your understanding.
True or false? If you open a file in write mode that already exists, the new data will be added to the file.
Is that true or false? Pause the video whilst you have a think.
Did you select false? Well done.
If a file already exists, then the original data in the file will be overwritten.
Okay, we're moving on to our first task of today's lesson, task A.
I'd like you to create a new programme that A, prompts the user to enter four player names.
B, allows the user to enter each name individually.
C, once the names have been entered, the name should be written to a text file called players-dot-text, or txt.
D, each player name should appear on a new line in the text file.
So here on the right hand side, we have a sample text output which shows the programme running in the IDE.
We also have a sample output from the text file.
So you can see we have four lines with the four names that the user has entered, Aisha, Jun, Laura, and Sam, with each text appearing on a new line in the file.
Pause the video here whilst you complete the activity.
How did you get on with your programmes? Did you manage to write to a file? Let's have a look at some sample solutions together.
There's more than one way to do this, so we're gonna have a look at two different ways.
So, this example, we have four lines of code which set the variables player one to player four, and ask for input from the user.
So player one is equal to input, enter player one.
And we just repeat that for the four players.
On line six, we then open our file.
So file is equal to open, open brackets, open speech marks, players.
txt, close speech marks, comma, and then we remember, really important here, we're opening it in write mode, 'cause we want to write to the file.
So W in speech marks, and then close our brackets.
Then on line seven, we're writing to the file, so file.
write, and we're using an f-string here, 'cause we're combining new line statements with our player variables.
So we've got player one, player two, player three, and player four.
And then, importantly, remember, when we've finished with a file, we should close it, so we have file.
close, open bracket, close bracket.
An alternative way to do this is to use a for-loop.
So in this example, we're initiating a string at the top of the file on line one, called players, but we're leaving it blank.
Then, on line three, we have our for-loop, which says for name in range, one to five, which we'll do four iterations of the loop, and then we have print, enter player name, so we're getting the user to enter the name.
We're then storing that as a variable called player.
And then on line six, we're adding that to the existing string.
So players is equal to players plus player, and the new line character.
So remember, we can join or concatenate strings together using the plus symbol.
Then we've got exactly the same lines of code on eight, nine, and 10, as we had before.
So we're opening the file in write mode, we're writing the data to the file, and then we're closing the file.
So remember, there's always multiple ways to approach an activity.
So even if your answer is slightly different from the two I've shown you, if you've managed to write to the file, well done.
Okay, we're now moving on to the second part of today's lesson, where we're going to append text to an existing file.
Append to a file works in a different way to writing to a file.
When you append to a file, you are adding new data to the end of the text file.
The original contents is not overwritten.
The mode character for appending to a file is an A, a lowercase "a".
Let's have a look at an example.
So we have file is equal to open.
We're using the text file from the previous activity, so players.
txt, but this time, after the comma, we have "a" in speech marks as our file handling mode for append.
There is no append method for text files.
The write method is used to write and to append files, which may not sound like it makes sense, but as long as you open the file in append mode, it won't overwrite the existing data.
Time to check your understanding.
What is missing from this programme to make it work correctly? Pause the video whilst you look carefully at the code.
Did you spot it? Well done.
We didn't have file.
close.
In some IDEs, the file must be closed in order for the programme to work as expected.
The file will remain open, and won't be updated.
You can add multiple lines of text to a file using one write line, but to make the lines of text appear on a new line in the file, you need to use the new line character, which is the forward slash n.
Here's an example.
We're opening the file, players.
txt, in append mode, and then we're doing a file.
write, open our brackets, in speech marks, we have the name Aisha, we have the new line character, and then we have the name Jun.
Close our speech marks and close our bracket.
Watch this video to see how to append to a text file.
Okay, we're now going to have a look at the append method instead.
So again, I have opened the Raspberry Pi code editor, and I've written the lines of code exactly the same as they appear in the slides.
So we have on line one, file is equal to open, and we're opening the text file players.
txt, and then we have our comma, and this time we're using the append mode.
So we have "a" in speech marks.
On line two, I have a write statement.
So I have file.
write, and in my brackets and speech marks, I have the name Aisha.
And then on line three, I have my file.
close to close the file once I have written to it.
Now if we just remind ourselves what was in players.
txt.
So if you remember, we originally entered the name Aisha and then we overwrote it with the name Jun.
So at the moment, players.
txt contains just one name, which is Jun.
Now if we go back to the programme and we run the programme, and then go back to players.
txt, we can see that Aisha has been added to the file.
So rather than replacing or overwriting the original content, we've appended that name to the end of the file.
Now, the Raspberry Pi code editor is quite kind, because it has automatically put Aisha's name on a new line for us.
Some IDEs will not do that for us.
So what we have to do in that case, so for example, you may have gone into your text file and you may have found that Aisha was actually on line one, right next to the word "Jun".
If that's the case, what you have to do is you have to use the new line character, which remember is the back slash N, before you write the name, and what that will do is it will put this down onto a new line.
You don't have to do that in the Raspberry Pi code editor, because it already does that for us.
Time to check your understanding.
True or false? This code will add the name Aisha to the end of the file, players.
txt, and then add the name Jun on the line underneath.
Look at the code carefully and have a think.
Did you select false? Well done.
The programme will add the name Jun on the same line.
To write Jun on a new line, you need to use the new line character.
Now the code has been amended to have the new line character, so Jun will appear on the next line in the text file.
Okay, we've come to the next activity of today's lesson, and you've done a fantastic job so far, so well done.
We're moving on to task B.
Open the starter programme at oak.
link/append-scores.
Note.
This programme already contains a text file called scores.
txt, which already contains some scores.
For part two, create a programme that performs the following.
A, prompts the user to enter their latest score.
B, adds a new score entry to the end of the scores.
txt file, using the format shown below.
So we have the score, which is 10,293, recorded at, and then followed by the date and time.
Note.
A new entry should appear at the bottom of the file on a new line.
Pause the video here whilst you complete the activity.
How did you get on? Did you manage to add a score to the file? Did it add it to the end of the file, on a new line? Great work.
Let's have a look at the code together.
So on line one, we're importing the module date time.
That's because we want to add a timestamp to when the score was entered.
Lines three and four were already in the file for you, and what they're doing is getting the current time from the date time module.
On line six, we're printing a message that says to the user "Enter your latest score", and on line seven, we're storing that input as the variable score.
On line nine, we have new score is equal to.
Now notice we have an f-string here and we've put in a new line character.
So that will make sure that the score is printed on the next line in the file, not on the same line as the last entry.
We then put the value held in score, recorded at, and then the value held in timestamp.
On lines 11 to 13, we're opening the file, writing new score to the file, and closing the file.
Remember, we needed to open the file in append mode, because we wanted to append to an existing file.
If we use the write mode here, it would overwrite the original contents of the file.
I'd now like you to open the starter programme at oak.
link/romeo-and-juliet.
Note.
This programme already contains a text file called romeojuliet.
txt.
For part four, create a programme that performs the following.
A, reads the contents of the Romeo and Juliet text file.
B, searches for all occurrences of the lowercase letter "a".
C, append the text file with a message at the bottom in the following format.
"Letter: a Occurrences" and then the number of occurrences, which here is 33.
Hint, you will need to read the file, then append to the file in separate steps.
Pause the video whilst you have a go at the activity.
How did you get on? Did you manage to complete the activity? Well done.
Let's have a look at some sample code together.
So on lines one to four, we're opening the file in read mode, and we're reading all of the text in the file.
So file is equal to open, romeojuliet.
txt, comma and in read mode, so we've used "r" there.
And then on line two, text is equal to file.
read.
So text is going to hold all of the contents of the file.
We've closed the file, and then we've printed the text.
On line six, we're setting a new variable that's short for occurrences, so OCC, and we're setting that to zero.
We then have a for-loop, which says, for letter in text, if letter is equal to A, then occurrence is going to be equal to occurrence plus one.
So we're incrementing the occurrence value or OCC.
We then open our file in append mode this time, and we write the details at the bottom.
So we're writing letter A on line 12, and then on line 13, we're doing another write statement, which is going to write the number of occurrences and include the number of occurrences held in the variable OCC.
Remember, we also close the file once we've done what we need to do with it.
Remember, if you need to pause the video here and make any corrections to your code, you can do that now.
Okay, we've come to the end of today's lesson, "writing to text files", and you've done a fantastic job, so well done.
Let's summarise what we've learned together today.
There are different modes for opening a file.
R for read, W for write, and A for append.
When you open a file in write mode, it creates a new file.
If that file already exists, then the file will be overwritten.
When you open a file and write to a file in append mode, it will add to the existing contents of the file.
It's good practise to close the file to save on system resources.
Some IDEs will not write to a file until it is closed.
I hope you've enjoyed today's lesson, and I hope you'll join me again soon.
Bye!.