Introduction
Writing files is one of the most important file-handling operations in Python. It allows programs to create new files, store data, generate reports, save logs, and update information permanently.
Python provides built-in functions for writing data into files efficiently.
Writing files is commonly used in:
-
Automation testing
-
Report generation
-
Log creation
-
Data storage
-
Configuration management
-
API testing
-
Web applications
In this tutorial, you will learn how to write files in Python, different writing modes, practical examples, real-world use cases, common mistakes, and best practices.
What is File Writing?
File writing is the process of storing data into a file.
Python uses the open() function along with write modes to create or modify files.
Example
file = open("sample.txt", "w")
file.write("Hello World")
file.close()
A file named sample.txt is created and the text is written into it.
Opening a File for Writing
Syntax
open(file_name, mode)
Write Mode (“w”)
The "w" mode is used to write data into a file.
Example
file = open("sample.txt", "w")
file.write("Python File Handling")
file.close()
Output File Content
Python File Handling
Creating a New File
If the file does not exist, Python creates it automatically.
Example
file = open("newfile.txt", "w")
file.write("New File Created")
file.close()
Overwriting Existing Content
The "w" mode removes existing content before writing.
Original File
Old Data
Example
file = open("sample.txt", "w")
file.write("New Data")
file.close()
Updated File Content
New Data
Writing Multiple Lines
Example
file = open("sample.txt", "w")
file.write("Python\n")
file.write("Java\n")
file.write("C++")
file.close()
Output File Content
Python
Java
C++
Using with Statement
The with statement automatically closes the file.
Example
with open("sample.txt", "w") as file:
file.write("Hello Python")
Appending Data to a File
Use "a" mode to add data without deleting existing content.
Example
with open("sample.txt", "a") as file:
file.write("\nNew Line Added")
Output File Content
Hello Python
New Line Added
Writing a List of Lines
The writelines() method writes multiple lines.
Example
lines = [
"Python\n",
"Java\n",
"JavaScript\n"
]
with open("languages.txt", "w") as file:
file.writelines(lines)
Output File Content
Python
Java
JavaScript
Writing User Input to a File
Example
name = input("Enter your name: ")
with open("user.txt", "w") as file:
file.write(name)
Sample Input
John
Output File Content
John
Writing Numbers to a File
Numbers must be converted to strings.
Example
age = 25
with open("age.txt", "w") as file:
file.write(str(age))
Output File Content
25
Writing Files in Automation Testing
File writing is heavily used in automation frameworks.
Example: Writing Test Results
with open("results.txt", "w") as file:
file.write("Test Passed")
Output File Content
Test Passed
Example: Saving API Response
response = '{"status":"success"}'
with open("response.json", "w") as file:
file.write(response)
Output File Content
{"status":"success"}
Example: Creating Execution Logs
with open("execution.log", "a") as file:
file.write("Test Started\n")
Real-World Example: Employee Records
Example
employee = "John"
with open("employees.txt", "a") as file:
file.write(employee + "\n")
Real-World Example: Student Information
Example
student = "Sarah"
with open("students.txt", "a") as file:
file.write(student + "\n")
Real-World Example: Product Inventory
Example
product = "Laptop"
with open("inventory.txt", "a") as file:
file.write(product + "\n")
File Modes Used for Writing
| Mode | Description |
|---|---|
| w | Write (overwrites existing content) |
| a | Append (adds content at the end) |
| x | Create file and write |
| w+ | Read and write |
| a+ | Append and read |
Using x Mode
The "x" mode creates a new file.
Example
file = open("newfile.txt", "x")
file.write("Created Successfully")
file.close()
Note
If the file already exists, Python raises an error.
Common Mistakes Beginners Make
Forgetting to Close the File
Incorrect
file = open("sample.txt", "w")
file.write("Hello")
Better Approach
with open("sample.txt", "w") as file:
file.write("Hello")
Writing Integers Directly
Incorrect
age = 25
file.write(age)
Output
TypeError
Correct
file.write(str(age))
Accidentally Overwriting Data
Incorrect
open("sample.txt", "w")
When you intended to append data.
Correct
open("sample.txt", "a")
Writing After File is Closed
Incorrect
file.close()
file.write("Hello")
Output
ValueError
Best Practices
Use with Statement
with open("sample.txt", "w") as file:
file.write("Python")
Use Append Mode Carefully
with open("logs.txt", "a") as file:
file.write("Log Entry\n")
Convert Non-String Data
file.write(str(number))
Handle Exceptions
try:
with open("sample.txt", "w") as file:
file.write("Data")
except Exception as e:
print(e)
Use Meaningful File Names
employee_report.txt
Instead of:
file1.txt
Advantages of Writing Files
-
Stores data permanently
-
Creates reports and logs
-
Supports automation frameworks
-
Easy to implement
-
Built into Python
Limitations of Writing Files
-
Incorrect mode may overwrite data
-
File permissions can cause errors
-
Large files may require memory management
Conclusion
Writing files is a fundamental Python skill that enables applications to store information permanently. Python provides multiple writing modes such as w, a, and x to support different use cases.
Whether you’re saving logs, generating reports, storing test results, or creating configuration files, file writing is an essential feature used in almost every software application.
Mastering file writing is an important step before learning CSV files, JSON files, Excel handling, and database operations.
Frequently Asked Questions (FAQs)
What function is used to write files in Python?
The write() method.
Example:
with open("sample.txt", "w") as file:
file.write("Hello")
What does “w” mode do?
It writes data to a file and overwrites existing content.
What does “a” mode do?
It appends data to the end of an existing file.
What is writelines() used for?
It writes multiple lines from a list into a file.
Why should I use with open()?
It automatically closes the file after use.
Key Takeaways
-
File writing stores data permanently.
-
open()is used to open files. -
"w"mode writes and overwrites content. -
"a"mode appends content. -
"x"mode creates new files. -
write()writes data into a file. -
writelines()writes multiple lines. -
with open()automatically closes files. -
File writing is widely used in automation testing and reporting.
-
Understanding file writing is essential before learning advanced file processing techniques.
