Files
open a file, and the with block closes it automatically when you're done:
with open("notes.txt", "w") as f: # "w" = write (overwrites) f.write("first line\n")
with open("notes.txt") as f: # default "r" = read text = f.read()
text.splitlines() splits the text into a list of lines. You can also loop over a file directly with for line in f:; each line includes its ending newline if present.
Mode "a" appends text without deleting existing contents. Neither write nor append mode adds line breaks for you: include "\n" in the text you write.
For structured data, json.dump(data, f) writes a dict or list into an open file as JSON, and json.load(f) reads it back. (Without the s, they work with files; dumps and loads work with strings.)
See it run
with open("notes.txt", "w") as f: f.write("first\n") f.write("second\n") with open("notes.txt") as f: lines = f.read().splitlines() print(lines)
Write a file, then read it back. The file lives in the program's working folder.
Practice files
Exercise 1
Write the three entries from todo in the code editor below to todo.txt, one per line. Then read the file back into a list tasks of lines.
Exercise 2
Read visits.txt, discard blank lines and surrounding spaces, and store the remaining names in visitors. Write those cleaned names to clean.txt, one per line in the original order, including repeat visitors. Use only files in the current directory.
Exercise 3
Read integers from sales.txt, ignoring blank lines. Store their sum in total. Append Total: N and a newline to audit.txt without deleting the existing header. Read the complete audit back into audit as a list of lines. Keep all files in the current directory.
Exercise 4
Save game settings and load them back. Write the settings dict to settings.json with json.dump(settings, f) inside a with open(..., "w") block. Then open the file again for reading, load it into loaded with json.load(f), and set volume to loaded["volume"].
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.