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

  1. Create a text file and write a list of your favorite books to it.
  2. Read the contents of the file and print them to the console.
  3. Append a new book to the file and print the updated contents.
  4. Create a log file to record your daily activities and read the log at the end of the day.

Happy coding!

Data AI Admin

Senior AI Lead having overall Experience of 10+ years in IT, Data Science, Machine Learning, AI and related fields.

Related Posts

Exploring Different Pandas File Formats

Data handling and manipulation are fundamental in data analysis. Pandas, a powerful Python library, supports various file formats for reading, writing, and converting data. Understanding these formats and their benefits…

Read more

Making Beautiful Plots with Seaborn in Python

Welcome to the sixth tutorial in our series on data analysis with Python! In this article, we’ll introduce you to Seaborn, a powerful Python visualization library built on top of…

Read more

Leave a Reply

You Missed

Exploring Different Pandas File Formats

  • June 28, 2024
Exploring Different Pandas File Formats

Making Beautiful Plots with Seaborn in Python

  • June 28, 2024
Making Beautiful Plots with Seaborn in Python

Mastering Data Visualization with Matplotlib

  • June 28, 2024
Mastering Data Visualization with Matplotlib

Data Cleaning and Preprocessing with Pandas

  • June 27, 2024
Data Cleaning and Preprocessing with Pandas

Exploring Data with Pandas: Series and DataFrames

  • June 27, 2024
Exploring Data with Pandas: Series and DataFrames

NumPy : Basic Operations and Arrays

  • June 27, 2024
NumPy : Basic Operations and Arrays