A file that already contains notes can be a place to add another line without losing what’s there. Python’s append mode writes new text at the end, while other modes can create or replace a file.

I’ll explain how the modes differ and show how to append text without replacing what’s already there.

TL;DR: Write a File in Python

Use open() with a context manager, choose w to replace content or a to append, then call write() with a string.

  • Use encoding=”utf-8″ for predictable text handling.
  • Use x when an existing file must not be overwritten.
  • Add \n where each written line should end.

What Does Writing a File in Python Mean?

A file object is the stream Python uses to access a file. In text mode, the stream accepts strings for writing.

For reading saved contents later, see the Python file reading guide.

Mode What it does Use it when
w Creates a missing file or clears an existing file before writing You intend to replace the old contents
a Creates a missing file or writes at the end You need to preserve existing text
x Creates a new file and raises FileExistsError if it exists Replacing a file would be unsafe

Choose the mode before writing. The + flag adds reading to a mode, but a write-only stream is simpler when the task only saves text. For reading the saved contents later, see the Python file reading guide.

How to Write a File in Python Step by Step

Open the path with the intended mode, write strings, and let the context manager close the file. A with block also closes it when an error occurs.

Step 1: Open a text file with an encoding

The filename is relative to the process’s current working directory. This example selects w because it creates or replaces the sample file.

from pathlib import Path

path = Path("notes.txt")
with path.open("w", encoding="utf-8") as file:
    file.write("First line\n")
    file.write("Second line\n")

Each write() call takes a string. The newline character is part of the string, so it separates the lines when the file is read back.

Step 2: Read back the saved text

After the write block closes, open the same path for reading and print its contents. I ran the example with python3 write_file_demo.py and got:

with path.open(encoding="utf-8") as file:
    print(file.read(), end="")

Reading the file back confirms the saved text and its line breaks.

Step 3: Append instead of replacing

Append mode writes at the end, so it preserves text already in the file. Use it for a simple log entry or another record that should follow earlier content.

with open("notes.txt", "a", encoding="utf-8") as file:
    file.write("Third line\n")

To write several strings, call writelines() with an iterable of strings. It does not insert line breaks for you, so include \n in each item that should end a line.

lines = ["First\n", "Second\n"]
with open("notes.txt", "w", encoding="utf-8") as file:
    file.writelines(lines)

For structured comma-separated records, use Python’s csv module rather than joining values with commas by hand. It handles CSV quoting rules that simple string concatenation does not.

File-Writing Errors and Next Steps

Many surprises come from the selected mode, the file path, or missing line breaks. Check these cases before changing the code.

Case Symptom Fix
Existing text disappears w truncates the file when opened Use a to preserve and extend it, or x to refuse an existing path
Lines run together write() and writelines() do not add separators Include \n in the strings
File appears in the wrong directory A relative path is resolved from the process working directory Use Path.cwd() to inspect that directory or pass an explicit path

A relative filename is resolved from the process’s current working directory, which may differ from the folder containing the script. If you save to a path supplied by a user or built from input, validate that path for your application before opening it.

Set encoding=”utf-8″ when the file must use UTF-8. A read-only destination or missing parent directory raises an operating-system error when opened for writing. Check the path and permissions before retrying.

Conclusion: Choose the File Mode First

A known path and a read-back check make a small file-writing task straightforward to verify. For more file operations, see the guide to printing to a file.

For details on file objects and text modes, see the Python open() documentation and the Python input and output tutorial.

FAQ

These short answers cover common choices when writing a text file in Python.

How do I write text to a file in Python?

Open it with open() in a with block, choose a writing mode such as w, and call write() with a string. Specify encoding=”utf-8″ for text.

Does writelines() add a newline?

No. Include newline characters in the strings when you want each item on its own line.

How do I add text without overwriting a file?

Open the file in append mode, a. It writes new text at the end and leaves existing contents in place.

Share.
Leave A Reply