Back to File Management

Oak National Academy

Lessons written by expert teachers in England, each with slides, a video and quizzes.

Their topic:
Programming: dictionaries and data files
For your topic:
File Management · Information and Communication Technology - 4IT1

Use these lessons alongside our lesson note, which covers your syllabus in full.

What this covers in your syllabus

1 lesson from Oak National Academy

Lesson 1 of 1 · GCSE level, ages 14 to 16

Writing to text files

By the end: I can write data to a new file and append data to an existing text file.

Key learning points

  1. There are different modes for opening a file, r (read), w (write) and a (append).
  2. When you open a file in write mode, it creates a new file. If the file already exists then the file will be overwritten.
  3. When you open a file and write to a file in append mode, it will add to the existing contents of the file.
  4. It is good practice to close the file once written to. Some IDEs will not write to a file until it is closed.

Keywords

write
a file handling mode that allows a program 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()
a file handling mode that allows a program to write extra data at the end of a file without erasing the existing contents of the file
overwrite
to replace information in (a computer file) with new information

A common mistake

Mistake: You have to create a new write() line for each line you want to add to a file.

In fact: You can write mutiple lines in one write() statement. But if you want the text to appear on separate lines, you must use the new line character.

Check what you learned

From Oak National Academy's exit quiz. Choose every answer that is right.

What happens when you open a file in write ("w") mode?
What will the following code do? ```file = open("example.txt", "w") file.write("Hello, world!") file.close()```
Which of the following is the correct way to open a file, write text to it, and close it properly in Python?
Which character is used to ensure text is added to a new line in a file?

A computing lesson by Oak National Academy licensed under the Open Government Licence (OGL) v3.0. Read the licence

The wording comes from each publisher. The layout and the links to your syllabus are ours.