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
open("notes.txt", "w")opens the file for writing. Thewithblock closes the file when the block ends, even if an error happens inside it. Closing the file writes any text that Python is still holding back to the file..write()does not add a new line for you, unlikeprint(). That is why each string ends with\n.encoding="utf-8"makes the file the same on every operating system. Without it, Windows may use a different encoding, and names like "Zoë" can be saved wrongly.end=""on the lastprint()stops it adding a second new line, because the text from the file already ends with one.
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.