Working with Strings in Python
A Python program can calculate results, process input, or analyze data while it is running.
Try it: Reading and Writing Text Files
How open() returns a file object with a position pointer, how read(), read(n), readline(), readlines() and for line in fh advance it (and return '' at the end), how 'w' and 'a' modes change the file, and why a closed file (after close() or a with block) can no longer be read.
How it works
- open(name, 'r') starts the pointer at 0; 'w' empties the file first; 'a' starts at the end.
- read() returns everything from the pointer to the end; read(n) at most n characters; readline() up to and including the next \n; each moves the pointer past what it returned.
- At the end of the file every read returns '' (an empty string), which is how loops know to stop; for line in fh reads line by line the same way.
- write() text waits in a buffer and reaches the file when it is closed (or the program ends); reading a 'w'/'a' file or writing an 'r' file raises io.UnsupportedOperation.
- close(), or leaving a with block, closes the file; any further read raises ValueError: I/O operation on closed file.
Default run (10 steps): Ready: notes.txt holds 4 lines (51 characters). Nothing is open yet. … Finished. notes.txt now holds "From: stephen\nSubject: meeting\nFrom: louis\nThanks!\n".
Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. One virtual text file with \n line endings (as on Linux/macOS), positions counted in characters (ASCII only), and a write buffer that is only flushed by close() or the end of the program.
Loading the simulation…
From Temporary Data to Saved Data
A Python program can calculate results, process input, or analyze data while it is running. Files allow that information to remain available after the program ends. File operations connect temporary in-memory work with information stored permanently on a computer.
File work follows a three-part pattern: open the file, perform an operation such as reading or writing, and close the file. The opening step selects the file and its mode. The working step uses the permissions provided by that mode. The closing step tells Python to finalize changes and release the file.
Choosing an Opening Mode
The open() function is the gateway to file operations. It takes a filename as a string and a mode that determines what the program is allowed to do with the file and what happens to existing content.
| Mode | Purpose | Effect on existing content |
|---|---|---|
| r | Read | Existing content is preserved |
| w | Write | Existing content is erased |
| a | Append | Existing content is preserved |
The three file modes described in the source material
Following the File Pointer
When a file is read line by line, readline() returns one complete line, including its newline character. After that call, the next read begins after the line that was returned. The file pointer therefore marks the current position in the sequence of file content.
f = open("poem.txt", "r")
line_one = f.readline()
line_two = f.readline()
line_three = f.readline()
f.close()- 1After opening, reading can begin from the file's current starting position.
- 2The first
readline()call returns the first line, including its newline character when that character is part of the line. - 3The second
readline()call begins after the first returned line. - 4The third
readline()call continues from the position after the second returned line. - 5Closing completes the file operation and releases the file.
- Open the file for reading.
- Read the first complete line.
- Read the next complete line.
- Read the next complete line.
- Close the file.
Recognizing the End of a File
A call to readline() normally returns a complete line. When there is no more content to read, it returns an empty string. That empty string is the signal a program can use to stop reading instead of continuing to request more lines.
What do you think happens?
What does readline() return after every available line has already been read?
Reveal answer
An empty string
The source defines an empty string as the result returned by readline() at end-of-file. A program can use that result as its stopping condition.
Writing and Closing Safely
Writing sends data from the Python program into a file opened for writing. The file should then be closed with f.close(). Closing tells Python to finalize changes and releases the file so other programs can use it.
A context manager using a with statement is an alternative way to have a file closed automatically. The essential idea remains the same: open the file, perform the work, and ensure that the file is closed afterward.
Mistakes with File Operations
Common mistake Opening a file in write mode when existing content should remain
What it looks likeopen("log.txt", "w")Why it failsWrite mode erases existing file content.
Do this insteadUse append mode when the existing content must be preserved and new data added.
Common mistake Treating an empty string from readline() as a normal line
What it looks likeContinuing to request lines after readline() returns ""
Why it failsAn empty string signals that the end of the file has been reached.
Do this insteadUse the empty string as the condition that stops the reading process.
Common mistake Skipping close() after file operations
What it looks likeOpening and writing to a file without closing it
Why it failsChanges may not be finalized, and the file may remain inaccessible to other processes.
Do this insteadCall f.close() or use a with statement for automatic closing.
Common mistake Confusing a returned line with the next file position
What it looks likeAssuming two readline() calls return the same line
Why it failsEach
readline()call advances through the file after returning a complete line.Do this insteadTrace each call as returning the current line and moving the pointer to the next position.
Practice the File Cycle
A file contains three lines. Describe what happens during three successive readline() calls, then describe the result of a fourth call. Finally, choose the safest mode for adding another line without removing the three existing lines.
Hints
- Each
readline()call returns one complete line and advances the file pointer. - At end-of-file,
readline()returns an empty string. - Append mode preserves existing content.
Tracing Four Reads
A file has exactly three available lines. What does each of four successive readline() calls represent?
- 1First call
It returns the first complete line and advances the file pointer.
- 2Second call
It returns the second complete line and advances again.
- 3Third call
It returns the third complete line and reaches the end of the available content.
- 4Fourth call
There is no more content, so
readline()returns an empty string.
The first three calls return lines; the fourth call returns an empty string that signals end-of-file.
Key Takeaways
- Use
open(filename, mode)to begin file operations. - Read mode retrieves content, write mode erases existing content before writing, and append mode preserves existing content while adding data.
readline()returns one complete line and advances the file pointer.readline()returns an empty string at end-of-file, which can be used to stop a reading loop.- Close files with
f.close()or use a with statement so changes are finalized and the file is released.