Labs ICT
Pro Login

Write Files

1 min read | Python Tutorial

Want the full learning experience?

Get structured courses, certificates, projects, and instructor support with LabsICT Pro.

Explore Pro Courses

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

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)

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