PythonMastery
Python programs · Files · beginner

Write to a file in Python

Create a text file and write lines to it with open() in 'w' mode and a with block. Shows why you add the new line yourself and how writelines() works.

To write a text file, open it in write mode ("w") and call .write() on the file object. If the file does not exist, Python creates it. If it does exist, its old contents are deleted first.

The program

python
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("Ada Lovelace\n")
    f.write("Grace Hopper\n")
    f.write("Alan Turing\n")

print("Written to notes.txt")

# read it back to check
with open("notes.txt", encoding="utf-8") as f:
    print(f.read(), end="")
output
Written to notes.txt
Ada Lovelace
Grace Hopper
Alan Turing

How it works

Writing a list of lines

writelines() writes every string in a list. It also does not add new lines, so add them in the loop:

python
names = ["Linus", "Hedy", "Margaret"]

with open("names.txt", "w", encoding="utf-8") as f:
    f.writelines(name + "\n" for name in names)

with open("names.txt", encoding="utf-8") as f:
    print(f.read(), end="")
output
Linus
Hedy
Margaret

You can also use print(name, file=f), which writes the text and the new line in one call.

Related programs: Append to a file.

Learn the idea: Files: Reading and Writing to Disk, File I/O, Pathlib, and Large Files