Path("report.txt").write_text(text, encoding="utf-8") writes a string to a file and replaces any existing contents. To preserve an existing file, open the path in mode x and handle FileExistsError. To add text to the end, use mode a and include any line breaks yourself.
Understand the three common write modes
Mode w opens a file for writing and truncates existing contents when the open succeeds. That can happen before your program finishes validating the data. Build and validate a short report in memory first. Mode x creates a new file and raises FileExistsError if the name is taken. It is useful for immutable exports or for practice examples where you want the old file to survive a rerun.
Mode a sends new writes to the end of the file and creates the file when needed. It does not insert a newline for you. If existing content lacks a final newline, a new record may run into the last one. Define whether every write must contain a complete line. Append mode by itself does not give a multi-process reporting program a complete record-level coordination policy.
Write known lines to a fresh destination
from pathlib import Path
path = Path("status-report.txt")
lines = ["Entries checked: 5", "Entries requiring review: 1"]
with path.open("x", encoding="utf-8", newline="\n") as handle:
handle.write("\n".join(lines) + "\n")
The example creates two newline-terminated lines. The explicit encoding makes the result portable, and the newline argument gives predictable LF line endings when writing. The path is relative to the current working directory. If you run it twice in the same folder, the second run should stop at the exclusive open and preserve the first report.
write() returns a count for that call, but a successful return does not establish that the complete report was written and closed. Closing can also raise an error. Report success after the context manager exits. For a list you already have, writelines() can accept the strings without joining first, but it does not add separators. Add each terminator explicitly if the output is intended to be one record per line.
Replace a complete report in one step
Suppose a daily report is used by another program. If it is overwritten in place and the writer crashes halfway, the reader can see a truncated report. One common approach writes to a temporary file in the destination directory, closes and validates it, and then calls os.replace() to replace the old path. Using the same directory helps avoid moving across file systems. Where the operating system and file system support the operation, readers opening the path see one committed file name rather than half-written bytes.
A temporary file requires cleanup on failure. Use the standard library’s temporary file facilities, close the handle before replacement where the platform requires it, and handle a destination that is locked or unavailable. File replacement and power-loss durability are different concerns. If the report is a critical record, design the workflow with explicit durability and retention requirements.
Give output a name that matches its lifecycle
For one authoritative daily dashboard, replacing latest.txt can be convenient. If a reviewer needs to compare the last three runs, give each generated report an immutable name or archive the previous version under its input date. A date in the file name should say whether it identifies the data period or the time the program ran. Those dates can differ when processing a late export.
An append log has a different lifecycle. The reader should understand how records are separated, whether the newest entry can be incomplete after a failure, and when the log is rotated. Keep ordinary summary output and error output separate if another program consumes the report. A disk or access error should be detectable by the process that scheduled the run.
Check what the next reader will see
For the example above, check that the saved file ends with a newline and contains exactly two report lines. To verify a file format that specifies exact line endings, compare its bytes instead of text. Use the format’s own writer for structured output. The CSV and JSON guide explains why quoting, embedded line breaks, and field types matter.
Keep exports outside the input directory where practical. Give generated output predictable names. A source directory scan that includes yesterday’s report by accident can quietly double its own input. If an output conflict should be visible to the user, report the full destination path and explain whether the old report remains. Test first in a temporary directory with an existing file and verify whether replacement, refusal or append matches the behavior you intended.