Writing to a file

The next step is being able to write to a file. If you have taken in some values during the running of a program, such as the user's scores, you will want to save this data for another occasion. You can write it to a file or a database. Here we will show how to write it to a text file.

To write to a file, you need to first open the file then use the write() method to write to it:

1
2
3
4
animals = ["dog","cat","horse"]
with open("new_animals.txt", mode="w",encoding="utf-8") as my_file:
    for animal in animals:
        my_file.write(animal+"\n")

Exercises

  1. Write a program which takes a list of six names and writes them to a file. Check that the file contains the six names on six separate lines.
  2. Create a file in Notepad which consists of a list of first names of your students. Read in the file, sort it into alphabetical order, then write it back to the file again. Check that your file is now in alphabetical order.