File I/O in Python should always use context managers (with open(...) as file:) to guarantee automatic file handle closure even if exceptions occur.
| Mode | Operations | Overwrites Existing? | Creates New File if Missing? |
|---|---|---|---|
'r' |
Read Text | No | Raises FileNotFoundError |
'w' |
Write Text | Yes | Yes |
'a' |
Append Text | No | Yes |
'x' |
Exclusive Creation | N/A | Yes (Raises FileExistsError if exists) |
'rb' / 'wb' |
Binary Read / Write | Depends on mode | Depends on mode |
from pathlib import Path
def file_io_demo(file_path: Path) -> None:
# Writing text cleanly via Context Manager
with open(file_path, mode='w', encoding='utf-8') as f:
f.write("Line 1: Log Entry
")
f.write("Line 2: System Status OK
")
# Appending text
with open(file_path, mode='a', encoding='utf-8') as f:
f.write("Line 3: Appended Audit Record
")
# Reading contents
with open(file_path, mode='r', encoding='utf-8') as f:
content = f.read()
print("--- File Contents ---")
print(content)
if __name__ == "__main__":
target = Path("sample_test_file.txt")
file_io_demo(target)
if target.exists():
target.unlink() # Cleanup
encoding='utf-8' explicitly when opening text files to prevent platform-dependent default encoding bugs.with Statement: Never call f = open(...) without a context manager; unclosed file handles cause resource leaks.'x' for Safe Writing: Use mode 'x' when creating new files to prevent accidentally overwriting an existing file.Write a context manager block that writes three lines to test.log and reads them back.
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
You've completed this section! Take a quick 5-question quiz to check your understanding.