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).
Every time you work with a file in Python, you follow a three-step process:
Open: Use the open() function to create a connection between your Python script and the file.
Process: Perform operations like read() or write().
Close: Use the close() method to free up system resources.
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.
| Mode | Description |
| '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. |
When you use 'w', Python creates a new file. If the file example.txt already exists, its previous contents will be deleted.
# 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.")
There are multiple ways to read data depending on how much of the file you need.
# 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
Use 'a' when you want to add new logs or data to an existing file without losing the old data.
with open("example.txt", "a") as file: file.write("Appending a new line at the end.\n")
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).
Copyright ©2025. All Rights Reserved Emblab THE RAVE INNOVATION