Lesson 16: Reading files
Files let you keep information even after the program ends. To read a file you open it with open("file.txt") and read its contents with .read(), which returns all the text as a single string. You can also loop over the file line by line. (The learning environment has no real disk, so we'll create a
open("file.txt") is like opening a notebook, and .read() reads everything in it at once. You can also read it line by line.
- open()
- open("file.txt") opens a file and returns an object you can read from.
- .read()
- .read() reads the whole file content and returns it as a single string.
- iterating lines
- for line in open("f.txt") yields one line per loop iteration.