Read and write files
Open text files and process them one line at a time.
Open a file with with open(path, "r", encoding="utf-8") as file:. Mode "r" reads an existing file. Mode "w" creates a file or replaces its existing contents. Use "a" to append instead.
Reading a file line by line keeps memory use steady for large inputs. Lines usually include a trailing newline, which .strip() removes along with other edge whitespace. The playground uses a temporary filesystem in the current run.
Line breaks separate the records stored in the file.
Try it yourself
Write "oak", "elm", "oak", "ash", and "oak" on five separate lines. Reopen the file and print the number of oak lines.
Target output
3Show a hint
Use \n between names in your string, and change the comparison inside sum.
Ready
Run your code to see the output here.
The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.
Show one solution
with open("trees.txt", "w", encoding="utf-8") as notes:
notes.write("oak\nelm\noak\nash\noak\n")
with open("trees.txt", encoding="utf-8") as notes:
print(sum(1 for line in notes if line.strip() == "oak"))