Module 24: Making Data Stick - Writing Files

Learn how to save your program's output and results permanently.

💾 Why Save Data? The Power of Persistence

Imagine your AI analyzes data, but when the program closes, *poof*! Everything is gone. That's not very useful! We need Data Persistence – the ability to save information beyond a single run of our program.

Writing to files is a fundamental way to achieve this. We can store results, logs, user data, configurations, and much more, making our applications truly functional.

🔑 Opening Files: Choosing Your Mode

Before writing, you need to open a file using the `open()` function, specifying a *mode*.

'w' – Write Mode

Overwrites! Opens the file for writing. If the file exists, its current content is deleted. If it doesn't exist, a new file is created.

'a' – Append Mode

Adds To End! Opens the file for writing, but adds new content to the end of the file without deleting existing content. If the file doesn't exist, it's created.

Choose wisely! Mode `'w'` can accidentally erase important data.

✍️ Writing Content with `.write()`

Once a file is open (in 'w' or 'a' mode), you use the `.write()` method.

The .write() method takes a string as input and writes that string to the file at the current position (end of file for 'a' mode, beginning for 'w' mode initially).

Important: .write() does not automatically add a new line. If you want each piece of text on a separate line, you must explicitly add the newline character: \n.

file.write("First line of text.") file.write("Second line, same line!") file.write("Third line." + "\n") # Add newline file.write("Fourth line starts fresh.\n")

🛡️ The Safe Way: `with open(...)`

Handling files requires care. What if your program crashes before you close the file?

Automatic Cleanup with `with`

Python's with statement provides a safer and cleaner way to work with files (and other resources).

When you use with open(...) as file_variable:, Python guarantees that the file will be properly closed automatically when you exit the `with` block, even if errors occur inside the block.

This is the recommended way to handle files in Python!

⚙️ Code in Action: Writing a Log File

Let's combine these concepts to write multiple lines to a file called `app_log.txt`.

# Use 'with' for safety, 'a' to append
with open('app_log.txt', 'a') as log_file:
    log_file.write("INFO: Application started.\n")
    log_file.write("DEBUG: Configuration loaded.\n")
    log_file.write("WARNING: Low disk space detected!\n")

print("Log entries added to app_log.txt") # Confirmation

Simulating `app_log.txt` Content

  

🧠 Quick Check!

Module 24 Theory Complete!

You've learned how to make your data persist by writing to files using Python! Practice makes perfect.
Head to the Practice Zone or challenge yourself with the Advanced Practice for this module.