File Input and Output Operations in Python
Files serve as persistent storage beyond the runtime memory of a program. Python provides a built-in streaming interface for creating, reading, updating, and removing files on disk.
Stream Initialization
Invoke open() to obtain a file handle:
handle = open("report.txt", mode="r", encoding="utf-8")
The mode argument controls access behavier:
r— read from the beginning (default)w— truncate and open for writinga— preserve existing bytes and appendx— exclusive creation; raisesFileExistsErrorif the path is takenb— binary access (e.g.,rb,wb)t— text decoding with the specifiedencoding(default)
After finishing, explicitly release system resources:
handle.close()
Sequential Reading
Slurp the entire contents into a string:
f = open("dataset.csv", "rt", encoding="utf-8")
payload = f.read()
print(payload)
f.close()
Process one record at a time to keep memory usage low:
f = open("dataset.csv", "rt", encoding="utf-8")
for record in f:
print(record.strip())
f.close()
Persisting Data
Overwrite mode (w) creates the file if absent, otherwise empties it:
f = open("notes.txt", "wt", encoding="utf-8")
f.write("Meeting scheduled for 10 AM\n")
f.write("Prepare slide deck\n")
f.close()
Append mode (a) inserts bytes at the current end-of-file:
f = open("notes.txt", "at", encoding="utf-8")
f.write("Follow-up required\n")
f.close()
Automatic Resource Management
A context manager guarantees closure regardless of control flow:
with open("dataset.csv", "r", encoding="utf-8") as f:
payload = f.read()
print(payload)
The same pattern applies to output:
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("Line one\n")
f.write("Line two\n")
Metadata and Cleanup
Validate existence before destructive actions:
from pathlib import Path
source = Path("notes.txt")
if source.is_file():
print("Located on disk")
else:
print("Not found")
Remove a file permanently:
from pathlib import Path
target = Path("temp.txt")
if target.exists():
target.unlink()
print("Deleted")