Chapter 14 of 15All chapters
Chapter 14 of 15
File handling
Reading and writing files without leaking handles.
open and with
open(path, mode) returns a file object. Wrapping it in with closes the file even if the code inside raises, which is why it is the only form worth writing.
- Modes: "r" read, "w" overwrite, "a" append, "x" create and fail if it exists.
- Add encoding="utf-8" explicitly, because the default depends on the machine.
Reading
read() gives the whole file as one string and readlines() gives a list. Looping the file object itself reads one line at a time, which is what you want for anything large.