Python Write Files

Writing to files lets your program save results, logs, and any other text, using either write mode to replace a file or append mode to add to it.

Writing text to a file

To store text on disk you open a file in a mode that permits writing, then call the write method on the file object. The two most common writing modes are "w", which starts the file fresh, and "a", which keeps existing content and adds to the end. Both create the file if it does not already exist.

Writing with the w mode

with open("report.txt", "w", encoding="utf-8") as f:
    f.write("Summary report\n")
    f.write("All systems normal\n")

print("Report written")
Note: The "w" mode empties the file the moment it is opened. If the file already held data you needed, that data is gone. Use "a" when you want to keep it.

Appending versus overwriting

Choosing between append and write is the most important decision when saving text. Append mode is ideal for logs and running records where each new entry should join the ones before it, while write mode suits files you regenerate from scratch each time.

ModeEffect on existing fileIf file is missing
"w"Contents are erased before writingA new file is created
"a"New text is added to the endA new file is created
"x"Raises FileExistsErrorA new file is created

Appending new lines

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("User logged in\n")
    f.write("Task completed\n")

print("Two lines appended")

Writing several lines at once

The write method takes a single string and does not add line breaks for you, so you include \n yourself where you want new lines. When you have a list of strings, writelines can send them all in one call, though it also leaves newline handling up to you.

Using writelines with a list

lines = ["apples\n", "bananas\n", "cherries\n"]

with open("fruit.txt", "w", encoding="utf-8") as f:
    f.writelines(lines)

print("List written to file")
  • write takes one string; add \n yourself to move to a new line.
  • writelines writes each string from a list without inserting separators.
  • Numbers must be converted with str before writing, since write expects text.
  • Data may stay buffered until the file closes, which the with statement handles for you.
Note: If you want to see written data on disk before the file closes, call f.flush(). Normally the with block flushes and closes automatically when it ends.