Writing to Files
To write to a file in Python, use open()
with "w"
(write) or "a"
(append) mode.
with open("output.txt", "w") as file:
file.write("Hello, world!")
"w"
creates the file if it doesn’t exist or overwrites it."a"
adds content to the end of the file.
Writing multiple lines:
lines = ["First line\n", "Second line\n"]
with open("output.txt", "w") as file:
file.writelines(lines)