Python 3 — Reading & Writing Files

🐍 Python 3 🟢 Lesson 12 📅 July 2026

Variables only persist while your program is running. The moment the script ends, the memory is cleared. To save data permanently, you must write it to files. Python provides simple built-in file operators for reading and writing files.

1 Writing to Files

To open a file, use the open() function. The first parameter is the file path, and the second is the mode: "w" (write) or "a" (append). We use the with block to guarantee the file is closed automatically:

Python 3 — File Writing ▶ Run Code
# Writing to a new file (overwrites old file if it exists)
with open("test_file.txt", "w") as file:
    file.write("Hello from Python File writing!\n")
    file.write("This data is saved to the disk.\n")

print("File written successfully!")
2 Reading from Files

To read a file, open it in read mode ("r") and read the contents using '.read()' (reads entire file) or a loop to process it line-by-line:

Python 3 — File Reading ▶ Run Code
# Reading the file we wrote above
with open("test_file.txt", "r") as file:
    content = file.read()
    print(content)
3 Appending to Files

If you open a file with "w" mode, Python will delete the existing file content. To preserve existing data and add text to the bottom, open the file in append ("a") mode:

Python 3 — Appending Files ▶ Run Code
with open("test_file.txt", "a") as file:
    file.write("Adding this new line without wiping old data!\n")
💡 Always Use 'with' Statement:

Historically, files were opened and closed manually using f = open(); f.close(). If your code crashed before the close line, the file remained locked. Using the with statement handles closing for you automatically, even during crashes.

4 Coding Challenge

Write a script that creates a file called 'notes.txt' and writes three checklist items in it. Then, reopen the file in read mode and print each line out to the console terminal.