open() / with
Try it yourself →Opens, reads or writes a file.
Syntax
with open(path, mod) as f:
...Description
The with block opens the file and closes it automatically when done. mode: 'r' read, 'w' write (overwrite), 'a' append. f.read() reads it all, f.write() writes.
Parameters
| path | The file's name/path. |
| mode | 'r' read, 'w' write, 'a' append. |
Example
with open("not.txt", "w") as f:
f.write("Hello file")
with open("not.txt") as f:
print(f.read())Expected output
Hello file
When to use?
Keeping logs, settings/record files, exporting data.
Common mistakes
- ⚠️ 'w' mode erases the file's old content; use 'a' to add to it.