2.8. builtin - File Input/Output (IO)¶
2.8.1. Syntax¶
Although there are many ways to work with files, by far the safest is with “Context Manager”, see builtin - Context Manager.
A Context Manager has an Enter and an Exit protocol that handles events. In terms of file IO,
with open
opens a file stream on Enter, and closes file stream on Exit, therefore files are
always closed down once the code is done streaming it.
# read a file
with open("filename.txt", "r") as f:
while True:
line = f.readline()
if not line:
break
# write a file
text = ["hello", "world"]
with open("filename.txt", "w") as f:
for line in text:
f.write(line + "\n")
Open file object modes:
r
: read onlyw
: write onlyx
: execution onlya
: append to existing fileb
: binary mode (this is combined withr
orw
+
: open for updating (reading/writing)