Writing Files
Use mode "w" to create/overwrite, "a" to append, and "x" to create exclusively (fails if file exists).
Writing Text
with open("output.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("Second line\n")writelines()
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w", encoding="utf-8") as f:
f.writelines(lines) # no newline added automaticallyprint() to File
with open("output.txt", "w", encoding="utf-8") as f:
print("Hello", file=f)
print(f"Pi = {3.14159:.4f}", file=f)Append Mode
with open("log.txt", "a", encoding="utf-8") as f:
f.write("New log entry\n") # adds to end, never overwritesExclusive Creation
try:
with open("new.txt", "x", encoding="utf-8") as f:
f.write("Brand new file")
except FileExistsError:
print("File already exists!")