Labs ICT
🎓 SIWES/IT Login

Write Files

1 min read | Python Tutorial
🎓

Doing SIWES / IT attachment?

Get a structured training programme, a supervised digital logbook, and a completion certificate with LabsICT SIWES / IT.

Explore SIWES / IT Training

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