Writing and Appending In Text Files

Writing to files is how Python programs save data permanently. Without file writing, all your program's output disappears the moment it stops running. In this post we cover every way to write files — safely, cleanly, and without losing data.


🛑 Critical Warning — The "w" Mode Danger

Before writing a single line of code, you must understand this. Opening a file in "w" mode has two very different behaviors:

  • File does NOT exist → Python creates a brand new empty file automatically. No error.
  • File DOES exist → Python instantly erases all existing content the moment you open it — even before you write anything.
# ⚠️ This ERASES "test2.txt" the moment it runs
file = open("test2.txt", "w")
# At this point the file is already empty — even if you close right now!
file.close()

There is no undo. The old data is gone. Keep reading to learn when to use "a" (append) mode instead.


🔹 1. write() — Write a Single String

write() inserts a string exactly as you type it — no extra spaces, no newlines added automatically. What you write is exactly what goes into the file.

file = open("test2.txt", "w")
file.write("Hello Python")
file.close()

📄 File content of test2.txt:

Hello Python

📌 write() Returns a Number:

Not many beginners know this — write() returns the number of characters written.

file = open("test2.txt", "w")
count = file.write("Hello Python")
print("Characters written:", count)
file.close()
Characters written: 12

Useful if you want to verify data was written correctly.


🔹 2. write() — Writing Multiple Lines

Python does not move to the next line automatically when you call write() again. Every call continues exactly where the last one ended. You must add \n manually to create new lines.

📌 Without \n — All on One Line (Wrong):

file = open("test2.txt", "w")
file.write("Hello")
file.write("Python")
file.write("World")
file.close()

📄 File content (not what you expected!):

HelloPythonWorld

📌 With \n — Correct Multiple Lines:

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

📄 File content (correct!):

Hello
Python
World

✅ Explanation:

  • \n is the newline character — it tells the file to start a new line
  • The last line usually does not need \n unless you want a blank line at the end
  • Each write() call continues from exactly where the previous one ended

💡 Real Scenario:

Saving user form responses, writing output of a calculation, logging messages to a text file.


🔹 3. writelines() — Write a List of Strings at Once

If you have a list of strings, writing them one by one in a loop is slow. writelines() takes the entire list and writes it all at once — much more efficient.

lines = ["Apple\n", "Banana\n", "Cherry\n"]

file = open("test2.txt", "w")
file.writelines(lines)
file.close()

📄 File content:

Apple
Banana
Cherry

⚠️ writelines() Does NOT Add \n Automatically:

# Without \n in list items
lines = ["Apple", "Banana", "Cherry"]

file = open("test2.txt", "w")
file.writelines(lines)
file.close()

📄 File content (everything on one line!):

AppleBananaCherry

Always include \n in each list item, or add it using a list comprehension:

lines = ["Apple", "Banana", "Cherry"]

file = open("test2.txt", "w")
file.writelines(line + "\n" for line in lines)   # Add \n on the fly
file.close()
Apple
Banana
Cherry

💡 Real Scenario:

Saving a list of names, writing processed data from a loop, exporting a filtered dataset to a file.


🔹 4. Append Mode "a" — Add Without Erasing

The "a" mode is the safe alternative to "w". It opens the file and places the cursor at the very end — so anything you write gets added after the existing content without touching it.

# Step 1: Create a file with some content
file = open("test2.txt", "w")
file.write("Hello\nPython\n")
file.close()

# Step 2: Append new data without erasing the old
file = open("test2.txt", "a")
file.write("New Line Added!\n")
file.write("Another Line!\n")
file.close()

📄 File content after append:

Hello
Python
New Line Added!
Another Line!

✅ Explanation:

  • "a" mode creates the file if it does not exist (just like "w")
  • If file exists — nothing is erased. Cursor starts at end
  • You can call append as many times as you want — data keeps stacking up

📌 w vs a — Quick Comparison:

Mode File exists? What happens to old data? Cursor starts at
"w" Yes ❌ Instantly erased Position 0 (start)
"w" No New file created Position 0 (start)
"a" Yes ✅ Kept, nothing erased End of file
"a" No New file created Position 0 (start)

💡 Real Scenario:

Writing to a daily log file — every time your program runs, it adds new entries without deleting yesterday's logs.


🔹 5. Writing Numbers and Other Data Types

Python files only accept strings. If you try to write an integer, float, or list directly — Python crashes with a TypeError.

❌ Wrong — Will Crash:

file = open("test2.txt", "w")
file.write(100)           # ❌ TypeError!
file.write(3.14)          # ❌ TypeError!
file.write([1, 2, 3])     # ❌ TypeError!
file.close()
TypeError: write() argument must be str, not int

✅ Correct — Convert to String First:

score = 100
pi = 3.14
fruits = ["Apple", "Banana", "Cherry"]

file = open("test2.txt", "w")

file.write(str(score) + "\n")              # Method 1: str()
file.write(f"Pi value: {pi}\n")            # Method 2: f-string
file.write(str(fruits) + "\n")             # Method 3: str() on list
file.write(", ".join(fruits) + "\n")       # Method 4: join() for clean list

file.close()

📄 File content:

100
Pi value: 3.14
['Apple', 'Banana', 'Cherry']
Apple, Banana, Cherry

✅ When to use which:

  • str(value) → simple conversion of any single value
  • f"..." → when mixing text and values in one line (most readable)
  • ", ".join(list) → when writing a list as a clean comma-separated line

🔹 6. with open() — The Safe Way to Write

When you write to a file, Python first stores the data in a temporary memory buffer. It only saves to disk when you call file.close(). If your program crashes before that — your data is lost.

The with open() statement solves this. It automatically calls close() — and therefore flushes the buffer to disk — the moment the block ends, even if an error occurs.

# write mode
with open("test2.txt", "w") as file:
    file.write("Hello\n")
    file.write("Python\n")
# File is automatically closed and saved here
# append mode
with open("test2.txt", "a") as file:
    file.write("New Entry\n")
# writelines with with open
lines = ["Line 1", "Line 2", "Line 3"]

with open("test2.txt", "w") as file:
    file.writelines(line + "\n" for line in lines)

Rule: Always use with open() when writing. It is safer, shorter, and guaranteed to save your data.


🔹 7. "r+" Mode — Read and Write the Same File

Sometimes you need to both read an existing file and write into it. The "r+" mode opens the file for both without erasing it.

# File already contains: "Hello\nPython\n"

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

    file.seek(0)                    # Go back to start
    file.write("Updated Content\n") # Overwrite from position 0
Original: Hello
Python

📄 File content after r+ write:

Updated Content
hon

⚠️ Note: "r+" writes over existing bytes — it does not insert or delete. If your new content is shorter than old content, old characters remain at the end. Use carefully.


🔥 All File Modes — Quick Reference

Mode Read Write Creates file? Erases existing?
"r" No
"w" Yes ⚠️
"a" No ✅
"r+" No
"wb" Yes ⚠️ (binary)
"ab" No ✅ (binary)

🚀 Pro Tips

  • Always use with open() — it guarantees data is flushed to disk
  • Use "a" mode for log files — data accumulates safely over multiple runs
  • Always convert numbers to string using str() or f-strings before writing
  • Use encoding="utf-8" when writing files with special characters or Hindi text
  • If you want to check if a file exists before overwriting, use os.path.exists():
import os

if os.path.exists("test2.txt"):
    print("File exists! Use append mode to be safe.")
else:
    with open("test2.txt", "w") as file:
        file.write("Fresh start!\n")

❌ Common Mistakes

  • Opening in "w" mode by accident → destroys all existing data instantly. No undo.
  • Forgetting \n between lines → all text gets merged on one line
  • Writing integers or lists directly → crashes with TypeError. Always convert with str()
  • Not using with open() → if program crashes, buffer is not flushed and data is lost
  • forgetting \n in writelines() list items → every string runs together with no line breaks

🔚 Conclusion

Python file writing is straightforward once you understand the key rules:

  • write() → write a single string. Add \n manually for new lines
  • writelines() → write a list of strings. Include \n in each item
  • "w" mode → creates or completely overwrites a file
  • "a" mode → adds to the end without erasing anything
  • with open() → always use this. Automatically saves and closes the file
  • str() or f-strings → always convert numbers before writing

Master these and you can build programs that save results, write reports, and maintain logs like a professional ⚡

Post a Comment

Do Leave Your Comments...

Previous Post Next Post

Contact Form