Concepts / Opening and Reading Files in Python

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.

  • Programming
Interactive lab

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

  1. open(name, 'r') starts the pointer at 0; 'w' empties the file first; 'a' starts at the end.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Educational simulation

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.

ApproachWhere the file name comes fromWhat happens with another file
Hardcoded file nameThe program codeThe code must be edited
User-selected file nameThe user's input at runtimeThe same program can be run again

A user-provided file name makes the program reusable across different files.

report.txtfile name in codefilenameuser inputEdit codeneeded for another fileSame programcan run on another filedifferent filedifferent file
What changes when the file name is fixed in the program versus supplied by the user?

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.

Code walkthrough
filename = input("Enter a file name: ")
file_object = open(filename)
  1. 1
    The program prompts the user and receives a file name.
  2. 2
    The response is stored in the variable filename.
  3. 3
    The value in filename is passed to open().
  4. 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.
input()user types a file namefilenamestored file nameopen()receives filenamefileopened for processingstores responsepasses valueopens named file
How does the filename typed by the user move from input() into the variable and then into open()?

Tracing One Run

Worked example

A User Chooses the File

Trace what happens when the program asks for a file name and the user enters notes.txt.

  1. 1
    Prompt

    input() asks the user to enter a file name.

  2. 2
    Response

    The user enters notes.txt.

  3. 3
    Storage

    The response is stored in the variable filename.

  4. 4
    Handoff

    The variable filename is passed to open().

  5. 5
    Opening

    open() receives the name notes.txt and locates and opens that file.

Result

The file name is chosen at runtime, so the code does not need to be edited for this run.

python
Output
Enter a file name: notes.txt

The 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.

input() thenopen(filename)program codeinput() thenopen(filename)unchanged program codenotes.txtfirst runsales.txtsecond runuser suppliesuser supplies
How can one unchanged program process different files on separate 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 like
    file_object = open("report.txt")
    Why it fails

    The program remains tied to that file name, so a different file requires a code edit.

    Do this instead

    Ask 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 like
    filename = input("Enter a file name: ")
    file_object = open("report.txt")
    Why it fails

    The user's response is collected but the fixed string is still passed to open().

    Do this instead

    Pass 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 like

    Replacing one literal file name with another before each run.

    Why it fails

    This gives up the reusability gained by accepting the file name at runtime.

    Do this instead

    Leave the program unchanged and provide the desired file name when input() prompts for it.

Practice the Handoff

EASY

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?

  • The program code changes automatically

  • The value supplied to open() changes

  • The input() call is removed

  • The variable is no longer used

Reveal answer
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

  1. 1
    A hardcoded file name limits reusability because a different file requires a code edit.
  2. 2
    input() can prompt the user for a file name.
  3. 3
    Store the user's response in a variable.
  4. 4
    Pass that variable to open() just as you would pass a literal string.
  5. 5
    The 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.

Related concepts

More concepts starting with O