Python Advanced: Reading & Writing Files

Goal of the Day

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.

Step 1: Opening Files

To work with files, use the open() function.


file = open("filename.txt", "mode")

Modes:

Step 2: Writing to a File


file = open("test.txt", "w")
file.write("Hello World\n")
file.close()

Explanation:

Step 3: Reading a File


file = open("test.txt", "r")
content = file.read()
print(content)
file.close()

Explanation:

Step 4: Appending to a 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.

Step 5: Practice – Saving User Input

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:

Practice Exercise

Write a program that saves a list of tasks (To-Do list)


with open("storage.txt", "r") as file:
    content = file.read()
    print(content)

Step 6: Tips & Best Practices