File Handling: Reading & Writing Files in Python
Introduction
Welcome to our lesson on file handling in Python! File handling is an essential skill for managing data in real-world applications. In this article, we’ll explore how to read from and write to files, cover different scenarios, and provide practical business examples to help you understand these concepts better.
Why is File Handling Important?
File handling allows you to store data permanently, retrieve it when needed, and manipulate it effectively. This is crucial for tasks such as saving user information, logging activities, and processing data files.
Basic File Operations
Python provides built-in functions to handle file operations. The most commonly used functions are open()
, read()
, write()
, and close()
.
Opening a File
The open()
function is used to open a file. It requires the file name and the mode in which the file should be opened.
'r'
– Read mode (default mode).'w'
– Write mode.'a'
– Append mode.'r+'
– Read and write mode.
Example:
file = open("example.txt", "r")
Closing a File
Always close the file after completing the operations to free up system resources.
file.close()
Reading from a File
1. Reading the Entire File
Use the read()
method to read the entire content of the file.
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
2. Reading Line by Line
Use the readline()
method to read one line at a time.
file = open("example.txt", "r")
line = file.readline()
while line:
print(line, end="")
line = file.readline()
file.close()
3. Reading All Lines into a List
Use the readlines()
method to read all lines into a list.
file = open("example.txt", "r")
lines = file.readlines()
for line in lines:
print(line, end="")
file.close()
Writing to a File
1. Writing Text to a File
Use the write()
method to write text to a file. If the file does not exist, it will be created.
file = open("example.txt", "w")
file.write("Hello, World!\n")
file.write("Welcome to file handling in Python.")
file.close()
2. Appending Text to a File
Use the append()
mode to add text to the end of the file without deleting the existing content.
file = open("example.txt", "a")
file.write("\nAppending new text to the file.")
file.close()
Working with Files Using with
Statement
Using the with
statement is recommended as it ensures the file is properly closed after its suite finishes, even if an exception is raised.
with open("example.txt", "r") as file:
content = file.read()
print(content)
Real-Time Business Scenarios
Example 1: Managing Employee Data
Imagine you need to store and retrieve employee details.
# Writing employee data to a file
employees = ["John Doe, Sales\n", "Jane Smith, Marketing\n", "Sam Brown, IT\n"]
with open("employees.txt", "w") as file:
file.writelines(employees)
# Reading employee data from a file
with open("employees.txt", "r") as file:
employee_list = file.readlines()
for employee in employee_list:
print(employee.strip())
Example 2: Logging System
A logging system records events or activities in a log file.
import datetime
def log_event(event):
with open("log.txt", "a") as log_file:
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
log_file.write(f"{timestamp} - {event}\n")
# Logging some events
log_event("User logged in.")
log_event("User updated profile.")
log_event("User logged out.")
# Reading the log file
with open("log.txt", "r") as log_file:
logs = log_file.readlines()
for log in logs:
print(log.strip())
Example 3: Data Processing
Processing data from a CSV file (comma-separated values).
# Writing data to a CSV file
data = [
"Name, Age, Department\n",
"John Doe, 30, Sales\n",
"Jane Smith, 25, Marketing\n",
"Sam Brown, 28, IT\n"
]
with open("employees.csv", "w") as csv_file:
csv_file.writelines(data)
# Reading data from a CSV file
with open("employees.csv", "r") as csv_file:
lines = csv_file.readlines()
for line in lines:
print(line.strip())
Conclusion
In this article, we covered the basics of file handling in Python, including how to open, read, write, and close files. We also discussed using the with
statement for better file management. Additionally, we provided real-world business scenarios to demonstrate practical applications of these concepts. Understanding file handling is crucial for managing data effectively in any Python application.
Practice Exercise
- Create a text file and write a list of your favorite books to it.
- Read the contents of the file and print them to the console.
- Append a new book to the file and print the updated contents.
- Create a log file to record your daily activities and read the log at the end of the day.
Happy coding!