Python

In Python, File Handling allows you to store data permanently in a file or read data from existing files. While variables store data in volatile memory (RAM) that disappears when a program stops, files store data on the hard drive (Persistent Storage).

1. Theoretical Overview

The File Handling Workflow

Every time you work with a file in Python, you follow a three-step process:

  1. Open: Use the open() function to create a connection between your Python script and the file.

  2. Process: Perform operations like read() or write().

  3. Close: Use the close() method to free up system resources.

The with Statement (Context Manager)

While you can manually open and close files, the modern and safest way is using the with statement. It automatically closes the file for you, even if an error occurs during processing. This prevents "memory leaks" and file corruption.

Common File Access Modes

ModeDescription
'r'Read (Default): Opens a file for reading; error if the file doesn't exist.
'w'Write: Opens for writing; creates the file if it doesn't exist or overwrites it if it does.
'a'Append: Opens for writing; adds data to the end of the file without deleting existing content.

2. Code Implementation

A. Writing to a File

When you use 'w', Python creates a new file. If the file example.txt already exists, its previous contents will be deleted.

Python
# Writing to a text file
with open("example.txt", "w") as file:
    file.write("Hello, welcome to EMBLAb!\n")
    file.write("This is a lesson on File Handling.\n")
    
print("File written successfully.")

B. Reading from a File

There are multiple ways to read data depending on how much of the file you need.

Python
# Reading the entire file
with open("example.txt", "r") as file:
    content = file.read()
    print("Full Content:\n", content)

# Reading line by line (Memory Efficient)
with open("example.txt", "r") as file:
    print("Line by Line:")
    for line in file:
        print(line.strip()) # strip() removes extra newlines

C. Appending to a File

Use 'a' when you want to add new logs or data to an existing file without losing the old data.

Python
with open("example.txt", "a") as file:
    file.write("Appending a new line at the end.\n")

3. Handling Different File Types

  • Text Files (.txt): Standard characters and strings.

  • Binary Files (.png, .exe, .dat): Used for non-text data; requires adding b to the mode (e.g., rb or wb).

Upcoming Course
Upcoming Course
Learn More
Instructor Tips
Instructor Tips
View Tips
Join Community
Join Community
Join Now