Introduction
Python's print function is a useful tool for displaying information in the console. However, there are situations where you might want to save this output to a file instead. This capability is particularly valuable for logging, creating reports, or saving program results for later analysis.
In this lab, you will learn how to redirect the output of Python's print function to a file. You will start with basic print operations, then progress to directing that output to files in different modes, and finally explore some practical applications of this technique.
Understanding the Basic Python print() Function
Before we redirect the output to a file, let's first understand how the print() function works in Python. The print() function is one of the most commonly used functions for displaying output in Python.
The print() Function Syntax
The basic syntax of the print() function is:
print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
Where:
value1, value2, ...: The values to be printedsep: The separator between values (default is a space)end: The string added after the last value (default is a newline)file: The file object where the output goes (default is the console)flush: Whether to forcibly flush the stream (default is False)
Let's create a simple Python script to demonstrate the basic usage of the print() function.
- Open the WebIDE and create a new file by clicking on the "File" menu and selecting "New File"
- Save the file as
print_basics.pyin the/home/labex/projectdirectory - Add the following code to the file:
## Basic print examples
print("Hello, Python!")
print("Multiple", "values", "with", "spaces")
print("Values", "with", "dashes", sep="-")
print("No newline at the end", end=" ")
print("This continues on the same line")
## Printing different data types
print("Integer:", 42)
print("Float:", 3.14)
print("Boolean:", True)
## Printing variables
name = "Alice"
age = 30
print("Name:", name, "Age:", age)
- Save the file by pressing Ctrl+S or clicking on "File" > "Save"
- Run the script by opening a terminal and typing:
python3 print_basics.py
You should see output similar to:
Hello, Python!
Multiple values with spaces
Values-with-dashes
No newline at the end This continues on the same line
Integer: 42
Float: 3.14
Boolean: True
Name: Alice Age: 30
This example demonstrates the basic functionality of the print() function, including how to print different values, customize separators, and control line endings.
Formatting Output with print()
You can also format the output of the print() function using f-strings (formatted string literals) or the format() method.
Let's add some formatted print examples to our file:
- Open the
print_basics.pyfile again - Add the following code at the end of the file:
## Using f-strings (Python 3.6+)
name = "Bob"
age = 25
print(f"Name: {name}, Age: {age}")
## Using format() method
print("Name: {}, Age: {}".format(name, age))
## Formatting numbers
price = 19.99
quantity = 5
total = price * quantity
print(f"Price: ${price:.2f}, Quantity: {quantity}, Total: ${total:.2f}")
- Save the file and run it again:
python3 print_basics.py
The new output should include:
Name: Bob, Age: 25
Name: Bob, Age: 25
Price: $19.99, Quantity: 5, Total: $99.95
Now that we understand the basics of the print() function, we can move on to redirecting its output to a file.
Redirecting print() Output to a File
Now that we understand how the print() function works, let's explore how to redirect its output to a file instead of displaying it in the console. The key is to use the file parameter of the print() function.
Writing Output to a File
To redirect the output of the print() function to a file, we need to:
- Open a file in write mode
- Pass the file object to the
print()function using thefileparameter - Close the file when we're done
Let's create a new Python script to demonstrate this:
- Create a new file named
print_to_file.pyin the/home/labex/projectdirectory - Add the following code to the file:
## Open a file in write mode
output_file = open("output.txt", "w")
## Redirect print output to the file
print("This is line 1 of our output file.", file=output_file)
print("This is line 2 of our output file.", file=output_file)
print("This is line 3 with numbers:", 42, 3.14, file=output_file)
## Close the file
output_file.close()
print("Output has been written to output.txt")
- Save the file and run it:
python3 print_to_file.py
- You should see the message "Output has been written to output.txt" in the console
- Let's check the contents of the
output.txtfile:
cat output.txt
You should see:
This is line 1 of our output file.
This is line 2 of our output file.
This is line 3 with numbers: 42 3.14
Using the with Statement (Recommended Approach)
A better way to work with files in Python is to use the with statement, which automatically takes care of closing the file even if an exception occurs. Let's modify our example:
- Create a new file named
print_to_file_with.pyin the/home/labex/projectdirectory - Add the following code to the file:
## Using the 'with' statement to handle file operations
with open("output_with.txt", "w") as output_file:
print("This line is written using the 'with' statement.", file=output_file)
print("The file will be automatically closed after this block.", file=output_file)
print("Numbers and other data types:", 100, 3.14159, True, file=output_file)
print("Output has been written to output_with.txt")
- Save the file and run it:
python3 print_to_file_with.py
- Check the contents of the new file:
cat output_with.txt
You should see:
This line is written using the 'with' statement.
The file will be automatically closed after this block.
Numbers and other data types: 100 3.14159 True
The with statement is the recommended approach for working with files in Python because:
- It automatically closes the file when the block ends
- It handles exceptions properly
- It makes your code cleaner and more readable
Now you know how to redirect the output of the print() function to a file using both traditional file handling and the more modern with statement approach.
Appending Output to Existing Files
In the previous step, we used the "w" mode when opening files, which creates a new file or overwrites an existing file. However, sometimes you might want to add new content to the end of an existing file without erasing its current contents. For this purpose, we use the "a" (append) mode.
Appending to a File
Let's create a script to demonstrate how to append output to an existing file:
- Create a new file named
append_to_file.pyin the/home/labex/projectdirectory - Add the following code to the file:
## First, create a file with some initial content
with open("append_example.txt", "w") as file:
print("This is the initial content of the file.", file=file)
print("Created on: 2023-09-01", file=file)
print("Initial content has been written to append_example.txt")
## Now, append to the file
with open("append_example.txt", "a") as file:
print("\nThis content is being appended to the file.", file=file)
print("Appended on: 2023-09-02", file=file)
print("Additional content has been appended to append_example.txt")
## Let's check the final content
print("\nFinal content of the file:")
with open("append_example.txt", "r") as file:
print(file.read())
- Save the file and run it:
python3 append_to_file.py
You should see output similar to:
Initial content has been written to append_example.txt
Additional content has been appended to append_example.txt
Final content of the file:
This is the initial content of the file.
Created on: 2023-09-01
This content is being appended to the file.
Appended on: 2023-09-02
Creating a Simple Log File
A common use case for appending to files is creating log files, where new entries are added without removing existing ones. Let's create a simple logging example:
- Create a new file named
simple_log.pyin the/home/labex/projectdirectory - Add the following code to the file:
import datetime
def log_message(message):
"""Append a timestamped message to the log file."""
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open("application.log", "a") as log_file:
print(f"[{timestamp}] {message}", file=log_file)
## Simulate some application events
log_message("Application started")
log_message("Processing data...")
## Simulate some user activity
user = "Alice"
log_message(f"User '{user}' logged in")
## Simulate an error
try:
result = 10 / 0
except Exception as e:
log_message(f"Error occurred: {e}")
log_message("Application shutting down")
print("Log entries have been written to application.log")
print("\nContents of the log file:")
with open("application.log", "r") as log_file:
print(log_file.read())
- Save the file and run it:
python3 simple_log.py
You should see output similar to:
Log entries have been written to application.log
Contents of the log file:
[2023-09-10 15:30:45] Application started
[2023-09-10 15:30:45] Processing data...
[2023-09-10 15:30:45] User 'Alice' logged in
[2023-09-10 15:30:45] Error occurred: division by zero
[2023-09-10 15:30:45] Application shutting down
Note that the actual timestamps will reflect your current date and time.
This simple logging example demonstrates a practical application of appending output to a file. Each time the script runs, it adds new log entries to the file without removing the previous ones. This is useful for tracking the history of an application's execution.
By using the append mode with the print() function, you can continuously add new content to your files, which is essential for many real-world applications like logging, data collection, and record keeping.
Creating a Practical Application - Report Generator
In this final step, we will create a more practical application that demonstrates how to use the print() function with file redirection to generate a formatted report. This example will show how this technique can be applied in real-world scenarios.
Building a Sales Report Generator
Let's create a script that generates a sales report based on some sample data:
- Create a new file named
sales_report_generator.pyin the/home/labex/projectdirectory - Add the following code to the file:
import datetime
## Sample sales data (product, quantity, price)
sales_data = [
{"product": "Laptop", "quantity": 5, "price": 899.99},
{"product": "Mouse", "quantity": 10, "price": 24.99},
{"product": "Keyboard", "quantity": 7, "price": 49.99},
{"product": "Monitor", "quantity": 3, "price": 149.99},
{"product": "Headphones", "quantity": 12, "price": 79.99}
]
def generate_sales_report(filename):
"""Generate a formatted sales report and save it to a file."""
today = datetime.datetime.now().strftime("%Y-%m-%d")
with open(filename, "w") as report_file:
## Print the report header
print("=" * 60, file=report_file)
print(f"SALES REPORT - Generated on {today}", file=report_file)
print("=" * 60, file=report_file)
print("", file=report_file)
## Print the table header
print(f"{'Product':<15} {'Quantity':<10} {'Price ($)':<10} {'Total ($)':<10}", file=report_file)
print("-" * 50, file=report_file)
## Print sales data and calculate totals
grand_total = 0
total_items = 0
for item in sales_data:
product = item["product"]
quantity = item["quantity"]
price = item["price"]
total = quantity * price
print(f"{product:<15} {quantity:<10} {price:<10.2f} {total:<10.2f}", file=report_file)
grand_total += total
total_items += quantity
## Print the summary
print("-" * 50, file=report_file)
print(f"{'Total':<15} {total_items:<10} {'':<10} {grand_total:<10.2f}", file=report_file)
print("", file=report_file)
print("=" * 60, file=report_file)
print("End of Report", file=report_file)
## Generate the report
report_filename = "sales_report.txt"
generate_sales_report(report_filename)
print(f"Sales report has been generated: {report_filename}")
print("\nContents of the sales report:")
with open(report_filename, "r") as file:
print(file.read())
- Save the file and run it:
python3 sales_report_generator.py
You should see output that includes:
Sales report has been generated: sales_report.txt
Contents of the sales report:
============================================================
SALES REPORT - Generated on 2023-09-10
============================================================
Product Quantity Price ($) Total ($)
--------------------------------------------------
Laptop 5 899.99 4499.95
Mouse 10 24.99 249.90
Keyboard 7 49.99 349.93
Monitor 3 149.99 449.97
Headphones 12 79.99 959.88
--------------------------------------------------
Total 37 6509.63
============================================================
End of Report
This example demonstrates how to create a nicely formatted report using the print() function with file redirection. The report includes headers, formatted data in a tabular layout, and summary information.
Creating a Dynamic Log Rotation System
Let's create one more example that demonstrates a log rotation system, which creates a new log file each time the script runs:
- Create a new file named
rotating_log.pyin the/home/labex/projectdirectory - Add the following code to the file:
import datetime
import os
def create_log_file():
"""Create a new log file with a timestamp in the filename."""
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
log_dir = "logs"
## Create logs directory if it doesn't exist
if not os.path.exists(log_dir):
os.makedirs(log_dir)
return os.path.join(log_dir, f"log_{timestamp}.txt")
def log_event(log_file, event_type, message):
"""Log an event to the specified log file."""
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(log_file, "a") as f:
print(f"[{timestamp}] [{event_type.upper()}] {message}", file=f)
## Create a new log file
log_filename = create_log_file()
print(f"Created new log file: {log_filename}")
## Simulate some application events
log_event(log_filename, "info", "Application started")
log_event(log_filename, "info", "Initializing modules...")
log_event(log_filename, "warning", "Configuration file not found, using defaults")
log_event(log_filename, "info", "Processing data batch #1")
log_event(log_filename, "error", "Failed to connect to database server")
log_event(log_filename, "info", "Retrying connection in 5 seconds")
log_event(log_filename, "info", "Connection established")
log_event(log_filename, "info", "Application shutting down")
print("\nLog file contents:")
with open(log_filename, "r") as f:
print(f.read())
- Save the file and run it:
python3 rotating_log.py
You should see output similar to:
Created new log file: logs/log_20230910_153045.txt
Log file contents:
[2023-09-10 15:30:45] [INFO] Application started
[2023-09-10 15:30:45] [INFO] Initializing modules...
[2023-09-10 15:30:45] [WARNING] Configuration file not found, using defaults
[2023-09-10 15:30:45] [INFO] Processing data batch #1
[2023-09-10 15:30:45] [ERROR] Failed to connect to database server
[2023-09-10 15:30:45] [INFO] Retrying connection in 5 seconds
[2023-09-10 15:30:45] [INFO] Connection established
[2023-09-10 15:30:45] [INFO] Application shutting down
This example demonstrates a more advanced application of file output in Python. Each time the script runs, it creates a new log file with a timestamp in the name, which helps with log organization and management.
These practical examples show how redirecting the print() function's output to files can be used to create useful applications like report generators and logging systems. The techniques you've learned in this lab can be applied to many real-world scenarios where you need to save program output for later reference or analysis.
Summary
In this lab, you have learned how to redirect the output of the Python print() function to files instead of the console. Here are the key concepts covered:
- The basics of the
print()function, including its parameters and formatting options - How to redirect
print()output to a file using thefileparameter - The difference between write mode ("w") and append mode ("a") when working with files
- Using the
withstatement for safer file handling - Practical applications of file output redirection, including:
- Creating log files
- Generating formatted reports
- Implementing a log rotation system
These techniques are valuable for many real-world scenarios, such as:
- Logging application events and errors
- Creating data reports
- Saving program output for later analysis
- Generating formatted text files
By mastering the redirection of the print() function output to files, you have gained a powerful tool for Python programming that will help you create more versatile and practical applications.



