Skip to main content

Writing & Appending Files


Writing Files ("w" Mode)

To create a new file or overwrite an existing one, open it in "w" mode:

with open("output.txt", "w") as file:
file.write("Hello, this file was created by Python!\n")
file.write("Writing code is awesome.")
Overwrite Warning

If output.txt already exists, all old content is permanently deleted and replaced with the new text. Use "w" mode only when you want to start fresh.


Appending Files ("a" Mode)

To add new content to the end of a file without deleting existing data, use "a" mode:

with open("output.txt", "a") as file:
file.write("\nThis line was added using Append mode.")

If the file does not exist, Python creates it automatically — just like "w" mode.


Writing Multiple Lines with writelines()

If you have a list of strings, you can write them all at once:

lines = ["Line 1\n", "Line 2\n", "Line 3\n"]

with open("multi.txt", "w") as file:
file.writelines(lines)
Newline Notice

writelines() does not add \n automatically. You must include newline characters yourself.


Practical Example: Saving User Notes

print("📝 Simple Notes App (type 'quit' to stop)")

with open("my_notes.txt", "a") as file:
while True:
note = input("Enter a note: ")
if note.lower() == "quit":
break
file.write(note + "\n")

print("Notes saved to my_notes.txt!")

Quick Summary

  • Write Mode ('w'): Creates a new file or completely wipes and overwrites existing file content.
  • Append Mode ('a'): Preserves existing data and adds new text at the end of the file.
  • file.write(string): Writes a string directly to disk (does not append newline \n automatically).
  • file.writelines(list): Writes a list of formatted strings to disk.

What's Next?

Let's look at how to handle missing files and permission denials safely in Handling File Errors!