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")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.
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.