Week 11: Interacting with Files
Learn how to read from and write to files in Python.
Explore Chapter 11Writing to Files.
You can also write data to files using Python.
`write()` Method
The `write()` method writes a string to the file. It does not automatically add a newline character, so you need to include `\n` explicitly if you want to start a new line.
file = open("output.txt", "w")
file.write("Hello, world!\n")
file.write("This is a new line.\n")
file.close()
If you open a file in `'w'` mode and the file already exists, its contents will be overwritten. If you want to append to an existing file, use `'a'` mode.
`writelines()` Method
The `writelines()` method writes a list of strings to the file.
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file = open("output.txt", "w")
file.writelines(lines)
file.close()