File Handling
Talking to the Hard Drive
Imagine you’re a hacker collecting logs from servers. Storing them in variables works for a moment, but what happens when you shut down the program? The data vanishes. To persist information, you need to read and write files. File handling is how Python communicates with the hard drive by saving data for later, retrieving it when needed, and managing it like a vault of secrets.
This chapter is about learning how to open, read, write, and manage files. Once you master this, your programs stop being temporary scripts and start becoming systems that remember.
Why File Handling Matters
- Persistence: Variables vanish when the program ends. Files keep data alive.
- Input/Output Beyond Console: Instead of typing everything manually, files let you automate data storage and retrieval.
- Flexibility: Files can store text, logs, configurations, or even binary data.
- Control: Python gives fine‑grained control over how files are opened, read, written, and closed.
Opening Files
file = open("data.txt", "r") # open for reading
content = file.read()
print(content)
file.close()
- Modes:
"r"→ read"w"→ write (overwrites existing file)"a"→ append (adds to existing file)"b"→ binary mode"x"→ create new file
Writing to Files
file = open("data.txt", "w")
file.write("Hello, Hacker!\n")
file.write("This is persistent data.")
file.close()
- Why? Writing stores information permanently.
"w"overwrites,"a"appends.
Reading from Files
file = open("data.txt", "r")
print(file.read()) # read entire file
file.close()
file = open("data.txt", "r")
print(file.readline()) # read one line
print(file.readlines()) # read all lines into a list
file.close()
- Why? Reading retrieves stored information for analysis or reuse.
Using with Statement
with open("data.txt", "r") as file:
content = file.read()
print(content)
- Why?
withautomatically closes the file, preventing resource leaks.
Managing Files
import os
# Check if file exists
if os.path.exists("data.txt"):
print("File found.")
else:
print("File not found.")
# Delete file
os.remove("data.txt")
- Why? File management ensures you can check, delete, or organize files safely.
The Hacker’s Notebook
- File handling gives persistence hence data survives beyond program execution. Modes (
r,w,a,b,x) define how files are accessed. - Writing stores data, reading retrieves it as two sides of the same coin. Always use
withfor safe file handling as it closes files automatically.
Hacker’s Mindset: treat files as your vaults. With them, you can log, store, and manage data across missions.

Updated on Jan 2, 2026