Python Basics - 06. File Input / Output¶
Reading from and writing to files is an essential part of programming. In Python, the built-in open() function paired with the with statement makes this extremely safe and straightforward.
Download Notebook¶
1. Writing to a File¶
To write to a file, use the open() function with the mode "w" (write). Warning: "w" mode will overwrite the file entirely if it already exists! Use "a" (append) to add text without deleting existing content.
The with block is an excellent practice because it automatically closes the file once the block is exited, avoiding memory or file locks.
file_path = "sample_text.txt"
with open(file_path, "w") as file_object:
file_object.write("Hello, Python File I/O!\n")
file_object.write("This is the second line.\n")
file_object.write("Data persistence is wonderful.")
print(f"Successfully wrote to '{file_path}'.")
Successfully wrote to 'sample_text.txt'.
2. Reading from a File¶
To read, you use the mode "r" (which is the default, so you can omit it). The read() method pulls the whole file as a single string.
print(f"Reading the entire content of '{file_path}':\n")
with open(file_path, "r") as file_object:
full_content = file_object.read()
print(full_content)
Reading the entire content of 'sample_text.txt':
Hello, Python File I/O!
This is the second line.
Data persistence is wonderful.
3. Reading Line by Line¶
For large files, loading everything into memory at once is slow and uses huge amounts of RAM. Instead, you can loop over the file object directly to process one line at a time.
print("Processing line by line:")
with open(file_path, "r") as f:
for line_number, line in enumerate(f, 1):
# Use strip() to remove the hidden newline character `\n` at the end of every line
print(f"Line {line_number}: {line.strip()}")
# Cleanup: Deleting the test file
import os
if os.path.exists(file_path):
os.remove(file_path)
print(f"\nCleaned up: '{file_path}' has been deleted.")
Processing line by line:
Line 1: Hello, Python File I/O!
Line 2: This is the second line.
Line 3: Data persistence is wonderful.
Cleaned up: 'sample_text.txt' has been deleted.