Skip main navigation

Writing to a file

Storing data is important as it enables the user to retain information for future use. Learn how to open and write to a text file in Python.

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.

This article is from the free online

Programming 103: Saving and Structuring Data

Created by
FutureLearn - Learning For Life

Reach your personal and professional goals

Unlock access to hundreds of expert online courses and degrees from top universities and educators to gain accredited qualifications and professional CV-building certificates.

Join over 18 million learners to launch, switch or build upon your career, all at your own pace, across a wide range of topic areas.

Start Learning now