Opening and Reading Files in Python
Hardcoding file names in your code limits reusability; you have to edit the code every time you want to process a different file.
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 Fixed Script to Reusable Tool
A program that always uses one file name can work, but it is limited. Whenever you want to process a different file, you must edit the code and replace the old file name. A more reusable approach is to let the user provide the file name while the program is running.
| Approach | Where the file name comes from | What happens with another file |
|---|---|---|
| Hardcoded file name | The program code | The code must be edited |
| User-selected file name | The user's input at runtime | The same program can be run again |
A user-provided file name makes the program reusable across different files.
The Filename Handoff
The reusable pattern has three parts. First, input() prompts the user for a file name. Second, the response is stored in a variable. Third, that variable is passed to open(). The variable carries the file name from the user's response into the function call. In this way, open() receives a user-provided value instead of a fixed literal string.
filename = input("Enter a file name: ")
file_object = open(filename)- 1The program prompts the user and receives a file name.
- 2The response is stored in the variable filename.
- 3The value in filename is passed to
open(). - 4
open()locates and opens the file named by that value.
input()asks the user for a file name and stores the response in filename.open()receives the variable containing the file name.
Tracing One Run
A User Chooses the File
Trace what happens when the program asks for a file name and the user enters notes.txt.
- 1Prompt
input()asks the user to enter a file name. - 2Response
The user enters
notes.txt. - 3Storage
The response is stored in the variable filename.
- 4Handoff
The variable filename is passed to
open(). - 5Opening
open()receives the namenotes.txtand locates and opens that file.
The file name is chosen at runtime, so the code does not need to be edited for this run.
Enter a file name: notes.txtThe important state change is the value held by filename. The program structure stays the same, but the value supplied by the user can be different each time the program runs.
Using the Pattern Carefully
Keep the responsibilities separate: input() obtains the file name, the variable stores it, and open() receives it. This makes the flow easy to identify and allows the same code to be used with different user-provided file names.
Common mistake Leaving the file name hardcoded in open().
What it looks likefile_object = open("report.txt")Why it failsThe program remains tied to that file name, so a different file requires a code edit.
Do this insteadAsk for the file name with input(), store the response in a variable, and pass the variable to open().
Common mistake Prompting for a file name but not using the variable.
What it looks likefilename = input("Enter a file name: ") file_object = open("report.txt")Why it failsThe user's response is collected but the fixed string is still passed to
open().Do this insteadPass filename to open() so the user's selection controls which file is opened.
Common mistake Changing the code for every new file.
What it looks likeReplacing one literal file name with another before each run.
Why it failsThis gives up the reusability gained by accepting the file name at runtime.
Do this insteadLeave the program unchanged and provide the desired file name when input() prompts for it.
Practice the Handoff
Write a short Python program that asks the user for a file name, stores the response in a variable named filename, and passes filename to open(). Then explain why the same code can be used with two different file names on two separate runs.
Hints
- Begin with
input()and a prompt asking for a file name. - Store the result returned by
input()in filename. - Use filename as the argument to
open(), rather than typing a fixed file name there.
What do you think happens?
If the same program contains input() followed by open(filename), what changes when the user enters a different file name on the next run?
Reveal answer
The value supplied to open() changes.
The user provides a different file name, that response is stored in the variable, and the variable is passed to open(). The program itself does not need to be edited.
Reusable File Processing
- 1A hardcoded file name limits reusability because a different file requires a code edit.
- 2
input()can prompt the user for a file name. - 3Store the user's response in a variable.
- 4Pass that variable to
open()just as you would pass a literal string. - 5The same unchanged program can run multiple times on different files.
Key Takeaways
- Hardcoding a file name makes a program dependent on one specific file.
input()lets the user provide the file name at runtime.- The response from
input()should be stored in a variable. - Pass the variable containing the file name to
open(). - This allows the same program to process different files without code changes.