open() takes a file path and a mode string — 'r' for reading text by default, 'w' for writing and overwriting existing content, 'a' for appending, and a 'b' suffix for binary mode — and returns a file object supporting iteration, reading, and writing. Forgetting to close a file can leak file handles and, for writes, leave buffered data never flushed to disk, which is why the `with` statement is the standard idiom: it guarantees the file is closed automatically, even if an exception occurs inside the block.
1Understanding open()
open() takes a file path and a mode string — 'r' for reading text by default, 'w' for writing and overwriting existing content, 'a' for appending, and a 'b' suffix for binary mode — and returns a file object supporting iteration, reading, and writing. Forgetting to close a file can leak file handles and, for writes, leave buffered data never flushed to disk, which is why the with statement is the standard idiom: it guarantees the file is closed automatically, even if an exception occurs inside the block.
Always specify the text encoding explicitly when opening text files — relying on the platform default encoding is a classic source of bugs that only show up when code runs on a different OS.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("Hello, file!")
with open("notes.txt", "r", encoding="utf-8") as f:
print(f.read())2Practical Example
Here is a real-world application of open() showing how it is used in production Python code.
with open("log.txt", "a", encoding="utf-8") as f:
f.write("New event logged\n")
with open("log.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip())3Best Practices
Follow these guidelines when working with open():
1. Always use a with block instead of manually calling close(), so the file closes even if an error occurs
2. Specify encoding='utf-8' explicitly for text files instead of relying on the OS default
3. Use exclusive-creation mode instead of write mode when you want writing to fail if the file already exists, to avoid accidentally overwriting data
Tip: Always specify the text encoding explicitly when opening text files — relying on the platform default encoding is a classic source of bugs that only show up when code runs on a different OS.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("Hello, file!")
with open("notes.txt", "r", encoding="utf-8") as f:
print(f.read())