Today you will learn:
By the end, you will be able to write programs that save data permanently, e.g., a shopping list, high scores, or notes.
To work with files, use the open() function.
file = open("filename.txt", "mode")
Modes:
"w" → write (overwrites existing file)"r" → read"a" → append (keeps existing content)
file = open("test.txt", "w")
file.write("Hello World\n")
file.close()
Explanation:
"test.txt" → file name"w" → write modewrite() → writes text to the file\n → new lineclose() → closes the file; very important, otherwise data may not be saved
file = open("test.txt", "r")
content = file.read()
print(content)
file.close()
Explanation:
"r" → read moderead() → reads the entire contentclose() → closes the file
file = open("test.txt", "a")
file.write("New line\n")
file.close()
Explanation: New data is added at the end of the file; old data remains.
A program that saves input and reads it on the next run:
# Save input
inputs = input("Enter something to save: ")
file = open("storage.txt", "a") # append
file.write(inputs + "\n")
file.close()
# Read inputs at start
file = open("storage.txt", "r")
content = file.read()
print("Previously saved inputs:")
print(content)
file.close()
Explanation:
Write a program that saves a list of tasks (To-Do list)
with open("file.txt", "r") as file: → Python closes the file automatically
with open("storage.txt", "r") as file:
content = file.read()
print(content)
close() or with\n