Writing and Creating Files in Python

You can write to a file in Python using the write() or writelines() methods. Opening a file in write mode "w" will create the file if it doesn"t exist or truncate it if it does.

Writing to a File:

Python
with open("example.txt", "w") as file:
    file.write("Hello, World!\n")
    file.write("This is a new line.")

Writing Multiple Lines:

You can write multiple lines at once using the writelines() method, which takes a list of strings:

Python
lines = ["First line\n", "Second line\n", "Third line\n"]

with open("example.txt", "w") as file:
    file.writelines(lines)

Appending to a File:

To append data to an existing file without overwriting it, open the file in append mode "a":

Python
with open("example.txt", "a") as file:
    file.write("\nThis line is appended.")

Writing to files is crucial for tasks such as logging, saving data, and generating reports.