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

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
different filedifferent filereport.txtfile name in codefilenameuser inputEdit codeneeded for another fileSame programcan run on another 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.

filename = input("Enter a file name: ") file_object = open(filename)

stores responsepasses valueopens named fileinput()user types a file namefilenamestored file nameopen()receives filenamefileopened for processing
How does the filename typed by the user move from input() into the variable and then into open()?

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.

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

Response: The user enters notes.txt.

Storage: The response is stored in the variable filename.

Handoff: The variable filename is passed to open().

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

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.

user suppliesuser suppliesinput() thenopen(filename)program codeinput() thenopen(filename)unchanged program codenotes.txtfirst runsales.txtsecond run
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.

  • Leaving the file name hardcoded in open().

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

    Fix: Ask for the file name with input(), store the response in a variable, and pass the variable to open().

  • Prompting for a file name but not using the variable.

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

    Fix: Pass filename to open() so the user's selection controls which file is opened.

  • Changing the code for every new file.

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

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