Writing files¶
Writing files is essential for saving data, creating output, and building applications that persist information. In this tutorial, you will learn how to create new files, overwrite existing ones, and append content.
Time commitment: 15–20 minutes
Prerequisites:
- Basic Python knowledge (variables, strings, lists)
- Completion of Reading files
Learning objectives¶
By the end of this tutorial, you will be able to:
- Write text to files using
open()with write mode - Append content to existing files
- Use exclusive creation mode to prevent overwriting
- Write multiple lines to a file
- Use
pathlib.Path.write_text()for simple write operations
Writing to a new file¶
To write to a file, open it with write mode "w". If the file does not exist, Python creates it. If it already exists, the contents are replaced.
from pathlib import Path
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, world!\n")
f.write("This is the second line.\n")
print(Path("output.txt").read_text(encoding="utf-8"))
!!! warning
Be careful with write mode `"w"` -- it will **overwrite** the entire file if it already exists. This is a common source of data loss.
Overwriting versus appending¶
If you open a file in write mode "w" that already contains data, the existing content is completely replaced.
from pathlib import Path
with open("output.txt", "w", encoding="utf-8") as f:
f.write("This replaces everything.\n")
print(Path("output.txt").read_text(encoding="utf-8"))
Appending to a file¶
To add content to the end of an existing file without removing what is already there, use append mode "a". If the file does not exist, Python creates it.
from pathlib import Path
with open("output.txt", "a", encoding="utf-8") as f:
f.write("This line is appended.\n")
f.write("And so is this one.\n")
print(Path("output.txt").read_text(encoding="utf-8"))
Exclusive creation mode¶
Exclusive creation mode "x" creates a new file but raises a FileExistsError if the file already exists. This prevents accidental overwriting.
from pathlib import Path
# Remove the file first so we can demonstrate exclusive creation
Path("safe-output.txt").unlink(missing_ok=True)
with open("safe-output.txt", "x", encoding="utf-8") as f:
f.write("Created safely.\n")
print(Path("safe-output.txt").read_text(encoding="utf-8"))
# Trying to create the file again raises an error
try:
with open("safe-output.txt", "x", encoding="utf-8") as f:
f.write("This will not work.\n")
except FileExistsError:
print("FileExistsError: the file already exists.")
Writing multiple lines¶
The writelines() method writes a list of strings to a file. Note that it does not add newline characters automatically – you must include them in each string.
from pathlib import Path
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("multi.txt", "w", encoding="utf-8") as f:
f.writelines(lines)
print(Path("multi.txt").read_text(encoding="utf-8"))
Writing with print()¶
You can use the print() function with the file parameter to write to a file. This is convenient because print() adds a newline automatically.
from pathlib import Path
with open("printed.txt", "w", encoding="utf-8") as f:
print("Line one", file=f)
print("Line two", file=f)
print("Line three", file=f)
print(Path("printed.txt").read_text(encoding="utf-8"))
Using pathlib.Path.write_text()¶
Path.write_text() is the simplest way to write text to a file. It opens the file, writes the content, and closes it – all in one step. Note that it always overwrites the existing content.
from pathlib import Path
Path("simple.txt").write_text("Simple content.\n", encoding="utf-8")
print(Path("simple.txt").read_text(encoding="utf-8"))
For appending content, use Path.open() with append mode.
Writing data from a list¶
A common task is writing data from a list, with each item on a separate line.
from pathlib import Path
names = ["Alice", "Bob", "Charlie"]
with Path("names.txt").open("w", encoding="utf-8") as f:
for name in names:
f.write(name + "\n")
print(Path("names.txt").read_text(encoding="utf-8"))
Exercises¶
Try these exercises to practise what you have learned.
Exercise 1: Create a file called shopping.txt with a list of five items, one per line. Then append two more items to the file.
Exercise 2: Write a function called save_lines that takes a file path and a list of strings, and writes each string to the file on a separate line. Use type hints and pathlib.Path.
Exercise 3: Write a function called append_timestamp that appends the current date and time to a file. Use datetime.datetime.now().
Solutions¶
from pathlib import Path
items = ["Bread", "Milk", "Eggs", "Butter", "Cheese"]
with open("shopping.txt", "w", encoding="utf-8") as f:
for item in items:
f.write(item + "\n")
with open("shopping.txt", "a", encoding="utf-8") as f:
f.write("Apples\n")
f.write("Bananas\n")
print(Path("shopping.txt").read_text(encoding="utf-8"))
from pathlib import Path
def save_lines(filepath: str | Path, lines: list[str]) -> None:
"""Write a list of strings to a file, each on a separate line.
Args:
filepath: The path to the file to write.
lines: A list of strings to write as lines.
"""
path = Path(filepath)
with path.open("w", encoding="utf-8") as f:
for line in lines:
f.write(line + "\n")
save_lines("colours.txt", ["Red", "Green", "Blue"])
print(Path("colours.txt").read_text(encoding="utf-8"))
from datetime import datetime
from pathlib import Path
def append_timestamp(filepath: str | Path) -> None:
"""Append the current date and time to a file.
Args:
filepath: The path to the file to append to.
"""
path = Path(filepath)
timestamp = datetime.now().strftime("%d/%m/%Y %H:%M:%S")
with path.open("a", encoding="utf-8") as f:
f.write(timestamp + "\n")
append_timestamp("timestamps.txt")
append_timestamp("timestamps.txt")
print(Path("timestamps.txt").read_text(encoding="utf-8"))
from pathlib import Path
for filename in ["output.txt", "safe-output.txt", "multi.txt", "printed.txt",
"simple.txt", "names.txt", "shopping.txt", "colours.txt",
"timestamps.txt"]:
Path(filename).unlink(missing_ok=True)
print("Temporary files removed.")
Summary¶
In this tutorial, you learned how to write and append to text files. Here are the key takeaways:
"w"mode creates or overwrites files"a"mode appends to existing files (or creates new ones)"x"mode creates files safely, raising an error if the file already existswritelines()writes a list of strings but does not add newlines automaticallyprint()with thefileparameter is convenient for formatted outputPath.write_text()is the simplest approach for writing entire files- Always specify
encoding="utf-8"for consistent behaviour
In the next tutorial, you will learn how to work with file paths using pathlib.