Python Docs
Python "with open()" — Full Cheat Sheet
What is "with open()"?
The with statement in Python automatically manages resources like files. When using with open(), Python opens the file, lets you work with it, and automatically closes it — even if exceptions occur.
This makes your code cleaner, safer, and avoids having to manually call f.close().
Basic Usage
Most common way to open and read a file:
with open("demofile.txt") as f:
print(f.read())Why Use "with open()"?
- Automatically closes the file
- Prevents memory leaks
- Avoids forgetting
f.close() - Cleaner and more readable code
- Handles exceptions safely
Write to a File
Using mode w will overwrite the file.
with open("notes.txt", "w") as f:
f.write("This is a new file.")Append to a File
Using mode a will add content at the end.
with open("log.txt", "a") as f:
f.write("New log entry\n")Read Only One Line
with open("demofile.txt") as f:
print(f.readline())Loop Through All Lines
with open("demofile.txt") as f:
for line in f:
print(line.strip())Open Multiple Files
with open("file1.txt") as f1, open("file2.txt", "w") as f2:
data = f1.read()
f2.write(data)Summary
| Mode | Meaning |
|---|---|
| r | Read (default) |
| w | Write (overwrite) |
| a | Append to end |
| x | Create file (error if exists) |
| t | Text mode (default) |
| b | Binary mode |
Final Note
Always use with open(). It is the safest, cleanest, and most Pythonic way to work with files.