Introduction
File handling is a fundamental part of programming, and writing data to files is one of the most common operations developers perform. Whether you are saving user information, generating reports, creating log files, or storing application data, writing files allows your program to save information permanently.
Python provides simple and powerful built-in functions for writing data to files. With just a few lines of code, you can create new files, overwrite existing files, append data, and even write binary data such as images and documents.
What is Python Write Files?
Python Write Files refers to the process of storing data into a file using Python programs.
Writing files allows applications to save information permanently so that it can be accessed later.
Python provides the open() function along with different file modes that determine how data is written to a file.
- Creating a new file
- Writing text to a file
- Overwriting file contents
- Appending new content
- Writing multiple lines
- Writing binary data
Syntax
The basic syntax for writing data to a file is:
file = open("filename.txt", "w")
file.write("Hello World")
file.close()
Explanation
- open() opens the file.
- “filename.txt” is the file name.
- “w” specifies write mode.
- write() writes data into the file.
- close() closes the file after writing.
File Modes Used for Writing
Python provides several modes that can write data.
| Mode | Description |
|---|---|
| w | Write mode (overwrites existing data) |
| a | Append mode (adds data at the end) |
| x | Creates a new file |
| wb | Write binary data |
| w+ | Read and write |
Writing Data Using write()
The write() method is used to write text to a file.
Example:
file = open("data.txt", "w")
file.write("Welcome to Python")
file.close()
Output in file:
If the file does not exist, Python creates it automatically.
Overwriting Existing Content
One important thing to remember is that write mode replaces existing content.
Suppose data.txt contains:
Hello World
Code:
file = open("data.txt", "w")
file.write("Python Programming")
file.close()
Output:
The previous content is completely removed.
Writing Multiple Lines
You can write multiple lines by including newline characters (\n).
Example:
file = open("students.txt", "w")
file.write("John\n")
file.write("Alice\n")
file.write("David\n")
file.close()
Output:
Alice
David
Using writelines()
Python provides the writelines() method for writing multiple lines at once.
Example:
students = [
"John\n",
"Alice\n",
"David\n"
]
file = open("students.txt", "w")
file.writelines(students)
file.close()
Output:
Alice
David
Appending Data to a File
Sometimes you want to add new content without deleting existing content.
Use append mode (a).
Example:
Suppose the file contains:
Python
Code:
file = open("data.txt", "a")
file.write("\nJava")
file.close()
Output:
Java
The existing data remains unchanged.
Using the with Statement
The recommended way to write files is using the with statement.
Example:
with open("data.txt", "w") as file:
file.write("Python File Handling")
Benefits:
- Automatically closes the file.
- Cleaner syntax.
- Better resource management.
- Reduces programming errors.
Creating a New File
The x mode creates a new file.
Example:
file = open("newfile.txt", "x")
file.close()
Output:
If the file already exists, Python raises an error.
Writing User Input to a File
Programs often save data entered by users.
Example:
name = input("Enter your name: ")
with open("users.txt", "a") as file:
file.write(name + "\n")
Input:
John
Output in file:
This is commonly used in registration systems.
Writing Binary Files
Binary files store non-text information such as:
- Images
- Videos
- PDFs
- Audio files
Use wb mode.
Example:
file = open("sample.bin", "wb")
file.write(b"Hello")
file.close()
Output:
Example
The following example creates a file and stores employee information.
with open("employees.txt", "w") as file:
file.write("Employee Name: John\n")
file.write("Department: IT\n")
file.write("Salary: 50000")
Output in file:
Department: IT
Salary: 50000
This is a simple example of storing structured information.
Real-life Example
Imagine you are building an institute management system.
Whenever a new student registers, their information is saved to a file.
student_name = input("Enter student name: ")
with open("students.txt", "a") as file:
file.write(student_name + "\n")
print("Student record saved.")
Input:
Rahul
Output:
File Content:
Rahul
Common Mistakes
1. Forgetting to Close the File
Incorrect:
file = open("data.txt", "w")
file.write("Python")
The file remains open.
Correct:
file = open("data.txt", "w")
file.write("Python")
file.close()
Or:
with open("data.txt", "w") as file:
file.write("Python")
2. Accidentally Overwriting Data
Incorrect:
file = open("data.txt", "w")
This deletes existing content.
Correct:
file = open("data.txt", "a")
Use append mode when preserving data is important.
3. Forgetting Newline Characters
Incorrect:
file.write("John")
file.write("Alice")
Output:
Correct:
file.write("John\n")
file.write("Alice\n")
Output:
Alice
4. Using writelines() Without Newlines
Incorrect:
names = ["John", "Alice", "David"]
file.writelines(names)
Output:
Correct:
names = [
"John\n",
"Alice\n",
"David\n"
]
5. Not Handling Exceptions
Incorrect:
file = open("data.txt", "w")
Correct:
try:
with open("data.txt", "w") as file:
file.write("Python")
except Exception as e:
print("Error:", e)
This makes the program more reliable.
Conclusion
Python Write Files is a powerful feature that allows developers to store data permanently on a computer. Using methods such as write() and writelines(), programmers can easily create files, overwrite content, append new information, and manage data efficiently.
Understanding file modes like w, a, and wb is essential for choosing the correct writing operation. The with statement simplifies file handling and helps prevent common mistakes related to file management.
Python Write to File – 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 Write to File – 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?