Writing Files
Learn how to write and append data to files in Python.
Python can create and write to files just as easily as reading them.
Writing to a File
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Python is great!\n")Appending to a File
with open("log.txt", "a") as file:
file.write("New log entry\n")Writing Lists
lines = ["Line 1", "Line 2", "Line 3"]
with open("output.txt", "w") as file:
for line in lines:
file.write(line + "\n")File Modes
"r"— Read (default)"w"— Write (overwrites)"a"— Append"x"— Create (fails if exists)