Python File Handling: Reading from and Writing to Files

Learn Python @

File handling is a crucial aspect of Python programming. Whether you’re working with text files, binary files, or CSV files, understanding how to read from and write to files is essential. In this comprehensive guide, we will explore Python’s file handling capabilities, providing detailed explanations, practical examples, and real-world scenarios to help you master this fundamental skill.

1. Introduction to File Handling

File handling is the process of working with files on your computer’s storage. Python provides a rich set of tools and functions to perform various file operations, including reading and writing.

2. Opening and Closing Files

Before you can read from or write to a file, you need to open it. Python’s open() function is used for this purpose:

# Opening a file in read mode
file = open("example.txt", "r")
# Performing file operations
# Closing the file

3. Reading Text Files

You can read text files line by line or as a whole using methods like readline() and read():

# Reading a text file line by line
with open("example.txt", "r") as file:
    for line in file:
# Reading the entire file at once
with open("example.txt", "r") as file:
    content =

4. Writing to Text Files

To write data to a text file, you can use the write() method:

# Writing to a text file
with open("output.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a test.")

5. Reading Binary Files

Binary files store data in a non-text format. You can read binary files similarly to text files:

# Reading a binary file
with open("binary.bin", "rb") as file:
    data =

6. Writing to Binary Files

Writing to binary files is also straightforward:

# Writing to a binary file
with open("output.bin", "wb") as file:
    data = b"\x48\x65\x6c\x6c\x6f\x2c\x20\x57\x6f\x72\x6c\x64\x21"

7. Working with CSV Files

CSV (Comma-Separated Values) files are commonly used for data storage. Python’s csv module makes it easy to work with CSV files:

import csv
# Writing to a CSV file
data = [["Name", "Age"], ["Alice", 25], ["Bob", 30]]
with open("data.csv", "w", newline="") as file:
    writer = csv.writer(file)

# Reading from a CSV file
with open("data.csv", "r") as file:
    reader = csv.reader(file)
    for row in reader:

8. Exception Handling

Handling exceptions is crucial when working with files to ensure that your code doesn’t crash due to file-related issues. Use try...except blocks to handle potential errors gracefully.

9. Examples

Let’s explore practical examples:

Example 1: Log File

# Writing log entries to a log file
import datetime
log_file = "app_log.txt"
with open(log_file, "a") as file:
    timestamp =
    log_entry = f"{timestamp}: User logged in."
    file.write(log_entry + "\n")

10. Best Practices

  • Always close files when you’re done with them (use with statement).
  • Use appropriate modes ("r", "w", "rb", "wb", etc.) for file operations.
  • Handle exceptions to prevent crashes and data loss.
  • Use context managers (with statement) to ensure proper file handling.

Learn Python Programming

Refer more on python Article here :

Author: user