DoAssignment study guide
A3.1 · Read and write an external file
Learn to read and write an external file through clear examples and targeted practice.
Ontario Grade 12 Computer Science
Programming Concepts and Skills
ICS4U A3.1 study lesson
A program can use information stored outside its running code. A text file is one way to keep that information so it can be read later or shared with another program. In this lesson, you will practise opening a file, reading or writing its contents, and closing it safely. The examples use Python 3; another classroom language may express the same operations differently.
What you will learn
- Explain how a program can get information from an external file and save information to one.
- Choose an appropriate file mode for reading, replacing a file's contents, or adding to its contents.
- Trace a short Python 3 example and state its preconditions and expected result.
1. Start with familiar input and output
In earlier programming, you may have received information from the keyboard and displayed results on the screen. A file provides another source or destination. Reading a file brings its saved contents into a program. Writing sends information from a program to a file.
An external file is separate from the program's source code. The program must refer to the file by a name or path. For these examples, assume the named files are in the program's working folder. A file's contents and location are part of the situation the program must handle; they are not created automatically just because the code refers to them.
A useful way to plan file work is to state the precondition, input, steps, and expected result. The precondition says what must already be true, such as a file existing before it is read. The input is the existing file content or the data the program will save. The steps describe the operations. The expected result says what the program displays or what is saved.
- A file can supply information to a program or receive information from it.
- Check whether a file must already exist before choosing the operation.
- State expected file contents as well as any expected screen output.
2. Open, use, and close a file
In Python 3, open connects the program to a file and returns a file object. The mode tells Python what the program intends to do. The basic modes used here are r for reading, w for writing, and a for appending. Reading with r requires the file to exist. Opening with w creates a file if needed, but replaces its previous contents if it already exists. Opening with a adds new content at the end and preserves the existing content.
The with open pattern is a practical way to manage the file. The indented statements use the open file; when that block ends, Python closes it. Closing matters because it finishes the program's use of the file and ensures that written content is properly saved. Keep file operations inside the block.
The read method gets the file's contents as text. The write method sends text to the file; it does not automatically add a line break. Include a newline character when the saved text should end that line. Text in quotes is what is written; the quote marks themselves are not part of the saved content.
Use w only when replacing old contents is intended. If the goal is to preserve old text and add more, a is the suitable basic mode. For a simple read, r makes the intention clear. These choices affect the file, not just the program's screen output.
- Use r to read an existing file, w to create or replace, and a to append.
- A write operation does not add a line break unless the text includes one.
- The with block provides a clear place for file use and closure.
3. Plan and trace file operations
Before reading, identify the exact file name and the content you expect it to contain. Trace what read returns, then distinguish that value from anything the program prints. Before writing, decide whether the previous file content should remain. This decision determines whether w or a fits the task.
A trace is a careful prediction based on the stated starting conditions. For example, if a file contains the text `Ready`, reading it gives the program that text. If a program writes `Done` using w, the resulting file contains `Done`, not the old text followed by `Done`. If it uses a instead, the new text follows the previous contents. The examples below make these starting conditions explicit.
Files may contain more than one line. A newline is part of the text content and marks where a line ends. When checking a result, describe the visible text and its line breaks so the expected saved content is unambiguous.
- Trace from the stated initial file contents; do not assume hidden contents.
- Separate text returned to the program from text printed to the screen.
- For writing, predict whether old contents are replaced or preserved.
4. Review before practising
For each task, ask four questions: What file is involved? Does it need to exist already? Should its old contents be replaced or kept? What exact text should be read, displayed, or saved? Answering these questions before coding helps prevent accidental loss of information and makes your expected result testable.
The three examples use a file that is stated to exist when reading, and state whether a destination already exists when writing. Their output descriptions are predictions from the supplied contents and code; the code has not been run here.
- A correct file mode depends on the intended result.
- Use precise preconditions so another person can follow your trace.
- Compare the final file contents with the task's intended contents.
Worked example
Read and display a file
Precondition: notes.txt exists in the working folder and contains exactly `Bring a pencil.` followed by a line break. Input: that file's text. Predict what the program displays.
Python 3
with open("notes.txt", "r") as file:
text = file.read()
print(text)- Open for readingThe stated precondition ensures notes.txt exists, so mode r is appropriate. The with block opens the file and ensures it is closed when the block ends.
- Read and displayread obtains the file's text. print displays that text; because the file text already ends with a line break, the display may include a blank-looking line after it.
Answer: The displayed text is `Bring a pencil.` on a line. The file is unchanged.
Check: The prediction follows from the given file contents and the read and print operations; it does not depend on an unmentioned file value.
Worked example
Write new contents to a file
Precondition: the program can create a file in its working folder. Assume report.txt already contains `Old draft`. Input: the text `Final version` and a line break. Predict the resulting file contents.
Python 3
with open("report.txt", "w") as file:
file.write("Final version\n")- Choose replacementThe task asks for new contents rather than preserving the old draft. Mode w creates the file if necessary and replaces its existing contents.
- Write the textwrite sends the supplied string to report.txt. The newline character ends the saved line. Leaving the with block closes the file.
Answer: After the block finishes, report.txt contains `Final version` followed by a line break. `Old draft` has been replaced.
Check: This result follows from mode w and the exact string passed to write. The program does not display the text on screen.
Worked example
Append without replacing
Precondition: log.txt exists and contains `Start` followed by a line break. Input: the text `Finished` and a line break. Predict the resulting file contents.
Python 3
with open("log.txt", "a") as file:
file.write("Finished\n")- Choose appendThe task requires keeping the existing text and adding another line. Mode a opens the file for appending instead of replacing its contents.
- Add the linewrite places the new string after the existing content. Since the existing text ends with a line break, the added word begins on the next line.
Answer: The resulting file contains `Start` on the first line and `Finished` on the second line, each followed by a line break.
Check: The original line remains because the file is opened in append mode, and the stated initial line break separates the two lines.
Common mistakes and how to avoid them
Using w when the intention is to add to existing text.
Correction: Use a when old contents must be preserved and new text added at the end.
Assuming read creates a missing file.
Correction: Reading with r requires the file to exist; include that as a precondition.
Expecting write to add a line break automatically.
Correction: Include a newline character in the written text when a line break is required.
Thinking print and write have the same destination.
Correction: print displays text; write sends text to the opened file.
Lesson summary
- Reading brings existing file text into a program; writing saves program text to a file.
- In Python 3, r reads, w creates or replaces, and a appends.
- The with open pattern keeps file operations together and closes the file when the block ends.
- Trace the starting contents and the exact written string to predict the final result.
Check your understanding
Question 1
A file already contains `A`. You want to keep it and add `B` at the end. Which mode matches that goal?
- r
- w
- a
- No mode is needed
Show answer and explanation
a
Mode a appends new text while preserving existing contents.
Question 2
A program opens an existing file in mode w and writes `New`. What happens to its old contents?
- They are replaced by the new contents.
- They are always placed after `New`.
- They are displayed but not changed.
- The file is read and then left unchanged.
Show answer and explanation
They are replaced by the new contents.
Mode w replaces existing contents when the file is opened for writing.
Question 3
What should be true before a program reads data from a file using mode r?
- The file must already exist.
- The file must be empty.
- The program must first open it in mode a.
- The file must contain a Python program.
Show answer and explanation
The file must already exist.
Mode r is for reading an existing file, so its existence is a precondition.
Key terms
- External file
- A file stored separately from the program's source code that a program can read or write.
- File mode
- The option given when opening a file that indicates whether it will be read, replaced, or appended to.
- Append
- Add new text at the end of existing file contents while keeping those contents.
- Precondition
- A condition that must be true before an operation or program step begins.
Continue through ICS4U
View the complete ICS4U Ontario Grade 12 Computer Science curriculum and lessons
About this lesson and its review
Published by DoAssignment. This reviewed lesson follows Ontario Grade 12 Computer Science (ICS4U), expectation A3.1. It is a study resource, not an official curriculum publication.
Before publication, content is checked for structure, mathematical or chemical notation, calculations, course boundaries, and readability. Errors can still occur, so corrections are welcomed.