Yes, you can write to a file in Python using the built-in open() function along with the write() method. Here's a simple example:
# Open a file in write mode
with open('example.txt', 'w') as file:
file.write("Hello, world!\n")
file.write("This is a new line.")
# The file is automatically closed after the with block
In this example:
- The
open()function is used to create or open a file namedexample.txtin write mode ('w'). - The
write()method writes the specified string to the file. - Using the
withstatement ensures that the file is properly closed after writing, even if an error occurs.
You can also append to a file by using the append mode ('a'):
# Open a file in append mode
with open('example.txt', 'a') as file:
file.write("\nThis line will be appended.")
This will add a new line to the end of example.txt without overwriting the existing content.
