Write with write()
write() writes a string to a file. It returns the number of characters written. Opening in "w" mode erases existing content.
with open("output.txt", "w") as f:
f.write("Hello, world!")
Try it Yourself →
Write Multiple Lines with writelines()
writelines() takes an iterable of strings. It does not add newlines — you must include them in each string.
lines = ["First line\n", "Second line\n", "Third line\n"]
with open("output.txt", "w") as f:
f.writelines(lines)
Try it Yourself →
Append Mode
Use "a" mode to add content at the end of an existing file without overwriting it. The file is created if it doesn't exist.
with open("output.txt", "a") as f:
f.write("Appended line\n")
Try it Yourself →