Reading and writing files
Python's built-in open() and the with statement are all you need to read, write, and safely handle files.
- Open a file with open() and read its contents
- Write text to a file with open() in write mode
- Use the with statement to ensure a file is always closed
- Distinguish read mode ('r'), write mode ('w'), and append mode ('a')
Every automation script eventually touches files: reading a list of tasks, writing a
report, loading a config. Python's built-in open() handles all of it. There is no
library to install — this is in the language itself.
Reading a file
The core pattern is three lines:
with open("data.txt", "r") as f:
content = f.read()
print(content)"r"is read mode. The file must already exist.f.read()returns the entire file contents as a single string.- The
withblock ensures the file is closed when the block ends.
If you want lines as a list instead of one big string, use f.readlines(), or iterate
directly:
with open("data.txt", "r") as f:
for line in f:
print(line.strip()) # strip() removes the trailing newlineWriting a file
with open("output.txt", "w") as f:
f.write("Done.\n")Mode "w" creates the file if it doesn't exist and overwrites it if it does. If you
want to add to an existing file without erasing it, use "a" (append) instead.
Why with is safer than manual close
You can open and close files without with:
f = open("data.txt", "r")
content = f.read()
f.close() # must remember thisThe problem: if an exception happens between open() and close(), the file stays open.
Open file handles leak resources and can cause data loss. The with statement handles
closing automatically — even if an exception is raised inside the block. Always prefer it.
with open(...) as f: is called a context manager. The object knows how to clean
up after itself when the block exits. Files are the canonical example, but the same
pattern appears for database connections, network sockets, and more.
Try it
The runner below uses io.StringIO to simulate a file as an in-memory string — the same
read/write API, no real filesystem needed in the browser:
The .seek(0) call rewinds to the start of the in-memory buffer before reading it back.
Real files on disk behave the same way — the file cursor tracks your position.
Where to go next
Next: paths and directories — before you can reliably open the right file, you need to understand how the filesystem tree works and why hardcoded paths break on other machines.