Python file write

In Python, writing to a file can be done using the open() function with a write mode. Here are the common methods to write data to a file:

Writing Text to a File

To write text data to a file, use the "w" mode (write mode). This will overwrite the file if it already


with open("filename.txt", "w") as file:
    file.write("Hello, World!")

"filename.txt": The name of the file you want to write to.

"w": Opens the file in write mode. If the file exists, it will be overwritten; if it doesn’t exist, a new file is created.

file.write(): Writes a string to the file.

Appending Text to a File

To add data to the end of an existing file without overwriting it, use the "a" mode (append mode).


with open("filename.txt", "a") as file:
    file.write("\nAppending this line to the file.")

"a": Opens the file in append mode, adding content to the end of the file without erasing existing data.

Writing Multiple Lines to a File

To write multiple lines at once, you can use writelines(). You need to provide a list of strings, where each string represents a line.


lines = ["First line\n", "Second line\n", "Third line\n"]
with open("filename.txt", "w") as file:
    file.writelines(lines)

Writing with Path from pathlib (Python 3.4+)

Using the write_text() method from pathlib provides a convenient way to write text data.


from pathlib import Path
Path("filename.txt").write_text("This is written with pathlib!")