
Code
Ink and Parchment
Variables vanish when a program ends. Files remember.
with open("voyage.txt", "w", encoding="utf-8") as f:
f.write("Left port\n")
f.write("Saw a whale\n")
with open("voyage.txt", encoding="utf-8") as f:
text = f.read() # the whole file as one string
print(text.splitlines()) # ['Left port', 'Saw a whale']
open(path, mode)gives you a file object. Modes:"r"read (the default),"w"write (creates the file, or erases it first!),"a"append to the end.f.write()does not add a new line for you. Add"\n".with ... as f:closes the file automatically when the block ends, even if an error happens. Always use it.encoding="utf-8"makes sure letters like é or emoji are saved the same way on every computer.
Pip tip: In PyQuest your files live on a virtual disk inside the browser. They work like real files, but disappear when you reload the page.
Assignment
- Complete
save_log(path, entries): write each string inentriesto the file on its own line (each followed by"\n"). - Complete
load_log(path): return a list of the file's lines without the newline characters.
- Complete
save_log(path, entries): write each string inentriesto the file on its own line (each followed by"\n"). - Complete
load_log(path): return a list of the file's lines without the newline characters.
main.py Python sleeping
Press Run to try your code, then Check to test it.