Python - 22
Python - 22: Reading & Writing Files
Python programs can save information to files and read it again later. In this browser course, we'll simulate a text file using a string variable.
Your challenge: Add several lines of text, split them into separate items, and loop through the saved information.
Simulate writing data
The variable notes acts like the contents of a small text file.
The characters \n mean “start a new line.”
For example: notes = notes + "Learn Python\n"
Split the saved text
notes.split("\n") breaks the string wherever a new-line character appears and creates a list of lines.
Read each line
Use a for loop to visit each item in the list. The final empty line can be skipped with: if line != "":
Try it: Add two more notes and see how they appear when the program reads the saved text.
Good Python habit: Keep file-related data organized one line at a time when each line represents a separate item.
Note: This browser lesson simulates file storage. In regular Python outside the browser, files are commonly opened with tools such as open(), read(), and write().
👀 Show Example Solution
notes = ""
notes = notes + "Buy milk\n"
notes = notes + "Learn Python\n"
notes = notes + "Build a small project\n"
print("Saved Notes:")
print(notes)
lines = notes.split("\n")
print("Reading Notes:")
for line in lines:
if line != "":
print(line)The string stores several lines of text, split() turns those lines into a list, and the loop reads each saved item one at a time.
