CodingNic

Files, Errors, and Automation

Writing Text Files

Files, Errors, and Automation 24 min read

Writing Text Files

Writing Text Files

Reading files is useful.

But many programs also need to save new data.

Examples:

  • Save notes
  • Store names
  • Create reports
  • Update logs
  • Export results

Python can write text into files.

What Does Writing Mean?

Writing means sending text from your program into a file.

The file can be created or updated.

Opening a File for Writing

Use open() with mode "w".

python
file = open("notes.txt", "w")

"w" means write mode.

Important Warning

If the file already has content, "w" replaces the old content.

Writing Text

Use write().

python
file = open("notes.txt", "w")
file.write("Hello World")
file.close()

Now the file contains:

text
Hello World

Better Way: with open()

python
with open("notes.txt", "w") as file:
    file.write("Hello World")

The file closes automatically.

Writing Multiple Lines

Use \n for a new line.

python
with open("notes.txt", "w") as file:
    file.write("Learn Python\n")
    file.write("Practice Daily\n")

File content:

text
Learn Python
Practice Daily

Append Mode

Use "a" to add new content without deleting old content.

python
with open("notes.txt", "a") as file:
    file.write("Keep Going\n")

Updated file:

text
Learn Python
Practice Daily
Keep Going

Writing User Input

python
name = input("Enter your name: ")

with open("users.txt", "a") as file:
    file.write(name + "\n")

This saves user names.

Common Beginner Errors

Using "w" by Mistake

This can erase old content.

Forgetting \n

Lines may join together.

Forgetting to Close

Use with open().

Code Along

Create a file named goals.txt.

Save:

text
Learn Python
Build Projects
Get Better

Mini Challenge

Build a journal saver.

Steps:

  • Ask the user to enter one note
  • Save the note into journal.txt
  • Add a new line after the note
  • Run again to keep adding notes

Hint: Use append mode.

Expected file example:

text
Today I learned files
Python is fun

Real World Use Case

Programs write reports, save notes, store usernames, create logs, and export data.

Quiz

  1. What does "w" do?
  2. What does "a" do?
  3. Why use \n?
  4. Why is with open() useful?

Assignment

Create a program that asks for 3 tasks and saves them into tasks.txt, one per line.

Summary

You learned how to create files, write text, append new content, save user input, and safely handle file writing in Python.