Sub topic 1
What `open()` returns
Prerequisites
You should know basic Python variables, functions, loops, strings, str versus bytes, and try/except.
What `open()` returns
open() returns a file object. A file object represents an open connection to a file and provides methods such as .read(), .write(), .readline(), and .close().
The first argument is the path. The optional mode controls the operation:
| Mode | Purpose |
|---|---|
| `"r"` | Read existing text |
| `"w"` | Write text, replacing existing content |
| `"a"` | Append text at the end |
| `"x"` | Create a new file, failing if it exists |
| `"b"` | Use binary data with another mode, such as `"rb"` |
| `"+"` | Allow both reading and writing, such as `"r+"` |
Reading with "r" fails if the file does not exist. Writing with "w" creates the file or truncates it immediately, so choose it carefully.
file = open("notes.txt", "r", encoding="utf-8")
text = file.read()
file.close()
print(text)The encoding argument tells Python how to translate bytes into characters. Explicitly choosing "utf-8" makes the program's behavior more predictable across systems.
Closing files reliably with `with`
An open file uses an operating-system resource. A with statement creates a context manager that closes the file when the indented block ends, including when an exception occurs.
with open("notes.txt", "w", encoding="utf-8") as file:
file.write("first line\n")
file.write("second line\n")The variable file is still a file object inside the block. Afterward, it is closed. Do not use it for further I/O.
Reading text files
.read() loads the remaining contents as one string. For large files, iterate over the file so Python processes one line at a time:
with open("notes.txt", encoding="utf-8") as file:
for line in file:
print(line.rstrip("\n"))Each line usually includes its trailing newline. rstrip("\n") removes that character without removing other surrounding spaces. Use .readline() when you need one line, or .read(size) to read a limited number of characters.
Exercise
Which mode should you use to add text while preserving the existing contents?
Show answer
Use append mode, "a", inside a with open(...) block.