Okay, let's put the concepts from this chapter into practice. We've learned how Python can interact with files on your computer, allowing programs to read existing data and save new information. This practical exercise will guide you through combining these skills to read from one file, modify the data, and write the results to another file.
We'll perform a common task: managing a simple list of names stored in a text file.
Our goal is to:
This simulates a basic data update process often found in applications.
First, let's write a short Python script to create our starting file, names.txt
. This file will contain three names, each on a new line.
# Define the initial list of names
initial_names = ["Alice", "Bob", "Charlie"]
# Specify the filename
filename = "names.txt"
# Use 'with open' in write mode ('w') to create and write to the file
try:
with open(filename, 'w') as file_object:
for name in initial_names:
file_object.write(name + "\n") # Add newline character after each name
print(f"Successfully created and wrote initial names to {filename}")
except IOError:
print(f"Error: Could not write to file {filename}")
Explanation:
initial_names
.with open(filename, 'w') as file_object:
to open names.txt
. The 'w'
mode indicates we want to write to the file. If the file exists, it will be overwritten; if not, it will be created. The with
statement ensures the file is automatically closed afterward.initial_names
. Inside the loop, file_object.write(name + "\n")
writes each name followed by a newline character (\n
). The newline character is important because it ensures each name appears on a separate line in the text file.try...except
block to catch potential IOError
if the file cannot be written for some reason (like permission issues).Run this script. You should now have a file named names.txt
in the same directory as your script, containing:
Alice
Bob
Charlie
Now, let's write code to read the names back from names.txt
.
# Specify the filename to read from
filename_to_read = "names.txt"
names_from_file = [] # Initialize an empty list to store names
try:
with open(filename_to_read, 'r') as file_object:
for line in file_object:
# Remove leading/trailing whitespace (including the newline character)
clean_name = line.strip()
names_from_file.append(clean_name) # Add the clean name to our list
print(f"Successfully read names from {filename_to_read}:")
print(names_from_file)
except FileNotFoundError:
print(f"Error: The file {filename_to_read} was not found.")
except IOError:
print(f"Error: Could not read from file {filename_to_read}.")
Explanation:
names.txt
using the read mode ('r'
), which is the default mode if none is specified, but it's good practice to be explicit.file_object
. In Python, iterating over a file object reads it line by line.line
read includes the newline character (\n
) at the end. We use line.strip()
to remove this and any other leading/trailing whitespace.names_from_file
list.try...except
blocks to handle FileNotFoundError
(if names.txt
doesn't exist) and general IOError
.Running this part should print the list ['Alice', 'Bob', 'Charlie']
.
Next, we prompt the user to enter a new name to add to the list.
# Get a new name from the user
new_name = input("Please enter a new name to add: ")
Explanation:
input()
function displays the prompt message and waits for the user to type something and press Enter. The entered text is stored in the new_name
variable as a string.Now, add the new_name
obtained from the user to the names_from_file
list we populated in Step 2.
# Add the new name to the list (only if it was successfully read)
if names_from_file: # Check if the list is not empty (reading was successful)
names_from_file.append(new_name)
print(f"Added '{new_name}'. Updated list: {names_from_file}")
else:
print("Cannot add name as the initial list was not loaded.")
Explanation:
.append()
method to add the new_name
to the end of the names_from_file
list.if names_from_file:
to make sure we only try to append if the list was successfully loaded in Step 2.Finally, we write the entire modified names_from_file
list to a new file, updated_names.txt
. Writing to a new file is often safer than overwriting the original immediately.
# Specify the new filename for the updated list
updated_filename = "updated_names.txt"
# Write the updated list to the new file (only if names exist)
if names_from_file:
try:
with open(updated_filename, 'w') as file_object:
for name in names_from_file:
file_object.write(name + "\n") # Write each name with a newline
print(f"Successfully wrote updated names to {updated_filename}")
except IOError:
print(f"Error: Could not write to file {updated_filename}")
Explanation:
updated_names.txt
in write mode ('w'
). This will create the file if it doesn't exist or overwrite it if it does.names_from_file
list (which now includes the user-added name).file_object.write(name + "\n")
writes each name from the list to the file, followed by a newline character.try...except
block handles potential writing errors.After running all the steps (or the combined script below), check your directory. You should see:
names.txt
: Containing the original three names.updated_names.txt
: Containing the original three names plus the name you entered.Here's the combined script putting all the steps together:
# --- Configuration ---
initial_filename = "names.txt"
updated_filename = "updated_names.txt"
initial_names_data = ["Alice", "Bob", "Charlie"]
# --- Step 1: Create Initial File (Optional, if not already present) ---
try:
# Try reading first to avoid unnecessary writes if file exists
with open(initial_filename, 'r') as f:
print(f"{initial_filename} already exists. Skipping creation.")
except FileNotFoundError:
print(f"{initial_filename} not found. Creating it...")
try:
with open(initial_filename, 'w') as file_object:
for name in initial_names_data:
file_object.write(name + "\n")
print(f"Successfully created {initial_filename}")
except IOError:
print(f"Error: Could not write initial file {initial_filename}. Exiting.")
exit() # Exit if we can't create the needed file
# --- Step 2: Read Names from File ---
names_from_file = []
try:
print(f"Reading names from {initial_filename}...")
with open(initial_filename, 'r') as file_object:
for line in file_object:
clean_name = line.strip()
if clean_name: # Avoid adding empty lines if any
names_from_file.append(clean_name)
print(f"Successfully read names: {names_from_file}")
except FileNotFoundError:
print(f"Error: The file {initial_filename} was not found. Cannot proceed.")
exit() # Exit if the source file isn't there
except IOError:
print(f"Error: Could not read from file {initial_filename}. Cannot proceed.")
exit() # Exit on other read errors
# --- Step 3: Get User Input ---
new_name = input("Please enter a new name to add: ")
# --- Step 4: Add New Name ---
# Basic validation: ensure the user entered something
if new_name.strip():
names_from_file.append(new_name.strip())
print(f"Added '{new_name.strip()}'. List is now: {names_from_file}")
else:
print("No valid name entered. List remains unchanged.")
# --- Step 5: Write Updated List to New File ---
print(f"Writing updated list to {updated_filename}...")
try:
with open(updated_filename, 'w') as file_object:
for name in names_from_file:
file_object.write(name + "\n")
print(f"Successfully wrote updated names to {updated_filename}")
except IOError:
print(f"Error: Could not write to file {updated_filename}")
print("\nProcess finished. Check names.txt and updated_names.txt.")
This practical example demonstrates the fundamental pattern of reading data, processing it (in this case, adding user input), and writing the result. You've used open()
, the with
statement, file modes ('r'
, 'w'
), read()
(implicitly by iteration), write()
, strip()
, and basic error handling (try...except
). Mastering these operations is essential for building applications that interact with stored data.
© 2025 ApX Machine Learning