Want to keep learning?

This content is taken from the Raspberry Pi Foundation & National Centre for Computing Education's online course, Programming 103: Saving and Structuring Data. Join the course to learn more.

Skip to 0 minutes and 3 secondsWhen programming, you can use many different data structures to store data, such as variables, lists, and dictionaries. Using these data structures is easy and convenient, but they have a flaw. As soon as your code ends, you lose your data. Storing data allows you to retain information for later use. To do this, you need to write the data to a file. So let's see how we're going to do this. First, we're going to create a new programme and we're going to save it. And we're going to name it "Write to file." Now, our first instruction has a couple of things we need to notice. First of all, we use the Open function to open a text file.

Skip to 0 minutes and 55 secondsThe name of the text file is names.txt. And this function takes a second parameter, which is w. And we use this parameter because we're going to write to the text file. Now, there's another variable, f, And we use this variable to handle our file more easily. Now, the second thing we need to do is ask for some data from the user. Now, be aware, if you have an existing file also called names.txt, Python will delete the contents of that file and overwrite it with the data from this project. So we need to take the data from the user. And for this reason, I'm going to use a variable called name. And I'm going to use the input function.

Skip to 1 minute and 51 secondsAnd I'm going to ask, what is your name? For example, hello, what is your name? After I've done that, a good idea is to use the print function to show the name that the user entered back to the screen just to make sure the code is running well up to there. So print "Hello" and then--

Skip to 2 minutes and 28 secondsnow, another good idea is to leave just a space there, so when we print back the name it doesn't come up as one word. Now, we need to write this back on the file. In order to do this, we're going to use the Write method. And we use f, our variable that we have to handle the file, and write. And inside the Write method, we're going to put the information that we need to add to the file, which in this case is the variable name. Now, a method is simply a function that belongs to or is part of another structure called a class, which in this case is a file.

Skip to 3 minutes and 12 secondsMethods work in the same way as functions, but are called slightly differently. Now, the Write method handles all of the tasks needed to open and write data to a file. The last thing we need to do is close the file. And for this reason, I'm going to use the Close method. It's good practise to close the file properly each time you finish. So the Close method is used to reduce the risk of data loss. Now let's run the programme. I'm going to add first name, and then I'm going to go to the text file. And as you can see, the name appears in the file. Now, run the code again entering a different name and then reopen the file.

Skip to 4 minutes and 4 secondsSo this time, I'm going to use a different name. And then I'm going to go back. And we can see that the name is now different. So you'll notice that the contents of the file have been overwritten with the new name. So we can create and we can replace files, but not update them. To add more than one name in the file, you will need to append to the file. The dictionary definition of append is to add to the end of a written document. And the same is true in programming. To enable your programme to append to a file, you only need to make two changes.

Skip to 4 minutes and 48 secondsSo the first change I'm going to make is I'm going to go to the open function and I'm going to change w2a, because now we need to append. And the second change-- I'm going to go to the Write method and I'm going to add a slash-n at the end. Slash-n stands for new line. You need to add a slash-n at the end because this inserts a new line after the name has been appended. Without the slash-n, your data will be saved to the file, but as a single long line of text. So now it's time to save and run the programme a few times. So I'm going to run it once more.

Skip to 5 minutes and 36 secondsAnd a second time.

Skip to 5 minutes and 42 secondsAnd now I'm going to go and check the text file. So in the text file, we can see that we added two names, and both names appear there. Laura appears on the first line. So we appended Laura at the end of the previous name that we added. Then we added a new line, therefore, Alicia, appears in that line underneath. Can you think of an example where you might want to write to a file rather than append it? Let us know in the comments section.

Skip to 6 minutes and 20 seconds[KEYSTROKE]

Writing to a file

Storing data is important as it enables the user to retain information for future use.

Data can be stored for many reasons. For example:

  • Sensor data for analysis in a spreadsheet
  • Configuration settings for a complex experiment

In programming you can use many different data structures to store data, such as variables, lists, or dictionaries. Although using these data structures is convenient, they have a flaw. As soon as the code finishes running your data is lost.

To store data for reuse you need to write to a file.

What you will need

During the course you will be using Python 3.

Image of Mu python editor with a simple hello world program

Hardware

  • A computer (macOS, PC with Windows or Linux, Raspberry Pi)
  • Internet connection (for software installation)

Software

  • Python 3
  • An integrated development environment (IDE) or code editor, e.g.
    • Mu
    • Thonny
    • IDLE (installed with Python 3)

Note: You will need to use a computer with Python installed — it is not possible to complete the programming tasks on a tablet or using online IDEs like Trinket or repl.it.

Writing to a file

You are going to create a program which will ask the user for their name and save it to a file called names.txt.

Create a new program and save it as write_to_file.py.

The first line of code uses the open() function to open a file called names.txt:

f = open("names.txt", "w")

The parameter w specifies that the file should be opened in write mode. The open file will then be referred to by the variable f for easier use.

Tip: If you have an existing file of the same name, names.txt, Python will delete the contents of that file and overwrite it with the data from this project. Now would be a great time to back up any data you don’t want to lose.

With the file created you now need to store something inside.

Use the input function to ask the user their name and capture their answer via keyboard input. Use the variable name to store the answer:

name = input("Hello, what is your name? ")

To show that the variable has stored the name correctly, you can print the name to the screen.

print("Hello " + name)

Next, write the contents of the variable name to the file f using the write() method:

f.write(name)

A method is simply a function that belongs to or is part of another structure called a class; in this case you are using the file class. A method works in the same way as a function, but is called slightly differently. The write() method handles all of the tasks needed to write data to a file.

The final step in the program is to close the file to ensure that the contents are saved correctly and reduce the risk of data loss. Use the close() method:

f.close()

Run your program and enter your name when prompted.

Image showing the output of the Python code. With the code asking the user their name.

Open the file

Using a text editor, such as Notepad or TextEdit, open the new names.txt file and you will see your name within.

Add another name

Run the code again and enter a different name and then reopen the names.txt file using a text editor.

When the code is run again, it overwrites the contents of the file with the new name. So when working with files in this manner you can create and destroy the contents of a file, but not update.

How can more than one name be added to names.txt? For this you need to learn how to append to a file.

Appending to a file

The dictionary definition of append is ‘to add to the end of a written document’, and the same is true in programming.

To enable your program to append to a file you only need to make two changes.

The first line created a link to the names.txt file and made it writable using w. To append to the file all you need to change is the w to an a.

f = open("names.txt", "a")

The second change is when the data is written to the file. You should still write the variable name to the file, but also add \n; this inserts a newline character after the name has been appended, so that the next name is written to the next line.

f.write(name + "\n")

Tip: It is common for new programmers to miss the \n. Their data will still be saved to the file, but as a single long line of text.

Run the code

Save and run the new program a few times, each time adding a new name.

Open names.txt in a text editor and you should see that each name is on a new line, creating a list of names.

Image showing the contents of names.txt.

Can you think of when you would write to a file rather than append? Discuss this in the comments section.

Share this video:

This video is from the free online course:

Programming 103: Saving and Structuring Data

Raspberry Pi Foundation