How to Write to a Text File in Python
To write to a text file in Python, open it with "w" and call write(). Use "a" to add text at the end.
Write text with open and write
Use with to close the file when the block finishes. Choose UTF-8 encoding.
with open("lesson-note.txt", "w", encoding="utf-8") as target:
target.write("Hello\n")
with open("lesson-note.txt", "r", encoding="utf-8") as source:
print(source.read(), end="")
This prints Hello. write() does not add a newline; \n supplies one.
Note: "w" creates a missing file and erases an existing file's contents.
Browser examples use temporary browser storage, not your personal files.
Append another line
Open with "a" to keep existing text and add more. This example resets its file first.
with open("lesson-log.txt", "w", encoding="utf-8") as target:
target.write("Started\n")
with open("lesson-log.txt", "a", encoding="utf-8") as target:
target.write("Finished\n")
with open("lesson-log.txt", "r", encoding="utf-8") as source:
print(source.read(), end="")
This prints Started, then Finished on the next line.
Write several lines
writelines() accepts strings. Include a newline in each string when you need separate lines.
with open("lesson-players.txt", "w", encoding="utf-8") as target:
target.writelines(["Ada\n", "Sam\n"])
with open("lesson-players.txt", "r", encoding="utf-8") as source:
print(source.read(), end="")
This prints the two names on separate lines.
See also: Reading text files, JSON.
Your turn
Write message to path using UTF-8 and "w". The supplied code reads it back.
path = "lesson-your-note.txt"
message = "Ready!\n"
with open(path, "w", encoding="utf-8") as target:
target.write("")
# add two lines: open path for writing with with, then write message
with open(path, "r", encoding="utf-8") as source:
print(source.read(), end="")
Expected output
Ready!