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!")
Python File Write – Questions and Answers
Q 1: How do you write to a file in Python?
Q 2: What happens if the file does not exist?
Q 3: Can writing overwrite existing content?
Q 4: How do you write multiple lines?
Q 5: How do you ensure the file is properly closed?
Python File Write – Objective Questions (MCQs)
Q1. Which mode is used to write to a file in Python?
Q2. What happens if the file already exists in "w" mode?
Q3. Which method writes data to a file?
Q4. Which mode is used to append data without overwriting?
Q5. How do you ensure text is written line by line?