COMPSCI4039 Chap.10 File Handling and Program Structure
File Handling and Program Structure
File Handling and Program Structure closes the opening week by connecting programs to permanent storage and by showing how larger programs are organised. Files persist after a program ends, live in folders and are located by paths relative to the current working directory. The recommended way to open a file is a with statement, which closes it automatically when the block ends.
Reading can take the whole file with read, one line with readline, every line as a list with readlines, or one line at a time with a for loop, which is the memory-efficient choice for large files. Each line arrives with its newline still attached, so strip is routinely applied.
The mode argument controls writing: w creates or replaces a file, a appends and preserves existing content, x creates a file only if it does not already exist, and rb and wb handle binary data. Exceptions such as a missing file are caught with try and except so the program can report the problem instead of crashing. CSV processing combines these steps.
The chapter also covers libraries, imports and aliases, and the main-function pattern.
What this chapter covers
- 01
Files, folders, paths and the working directory
- 02
Opening files safely with with
- 03
Reading with read, readline, readlines and loops
- 04
Newlines and strip
- 05
Write, append, exclusive and binary modes
- 06
Catching file errors with try and except
- 07
Reading and writing CSV data
- 08
Libraries, imports and the main-function pattern
Worked example · free
Predict a file after two different modes
- 1Mode w creates the file and writes a and a newline. This mark allocation is a practice device of our own, not an official university scheme.
- 1Mode a keeps that content and adds b and a newline at the end.
- 1readlines returns a list with one string per line: two strings, each ending in a newline.
- 1Applying strip to each removes the newlines, leaving a and b.
Key terms
- Working directory
- The folder a running program uses to resolve relative file paths.
- Exception handling
- Catching a run-time error with try and except so the program can respond instead of crashing.
- CSV file
- A text file that stores a table as lines of comma-separated values.
- Library import
- Bringing pre-written code into a program with an import statement.
- Main-function pattern
- Placing a program's entry point in main and calling it only when the file runs directly.
File Handling and Program Structure FAQ
Why does my file lose its old contents?
Opening a file in mode w creates it if necessary and empties it if it already exists, so earlier data is lost. Use mode a to add to the end while keeping existing contents, or mode x to refuse when the file is already there.
Why do printed lines from a file have blank lines between them?
Each line read from a file still ends with its newline character, and print adds another. Call strip on the line before printing, or print with end set to an empty string, to remove the extra blank line.
What does if __name__ == '__main__' do?
It lets a file act both as a program and as a library. When the file runs directly, the special variable __name__ holds the string '__main__' and the guarded code runs; when another program imports the file, the guarded code is skipped and only definitions load.
How do I stop a missing file from crashing my program?
Put the code that opens the file inside a try block and add an except FileNotFoundError block that prints a helpful message. The program then reports the problem and carries on, or ends tidily, instead of stopping with an error. Checking first with os.path.exists is an alternative when you only need to know whether the file is there.
Exam move
Practise file handling hands-on, then summarise it on paper for the examination. Create a small text file, read it in each of the four ways the lecture shows, and print what each returns between vertical bars so that newlines become visible. Then predict, before running, what a sequence of opens in different modes leaves in a file, and check by reading it back.
Write a short program that opens a missing file inside try and except and prints a helpful message, and compare its behaviour with the unprotected version. For CSV data, write the full open, read, process and output pipeline: skip the header, strip and split each line, cast numeric fields and accumulate a result.
Finally, restructure one of your scripts into separate functions for reading, processing and output, called from main under the name guard, and import one function from it into a second program to see the guard working. Keep a one-line summary of each mode for your revision notes.
Working through File Handling and Program Structure in COMPSCI4039? Sia is AskSia’s AI Computer Science tutor — ask any COMPSCI4039 File Handling and Program Structure question and get a clear, step-by-step explanation grounded in how COMPSCI4039 is taught and assessed. Read this chapter free, then take your hardest questions to Sia.