Writing data to files is one of the most common tasks in Python programming. While reading files retrieves stored information, writing files allows programs to save new data permanently. Almost every real-world application writes information to files, including student management systems, banking software, web applications, data analytics tools, and machine learning projects.
Whenever a user submits a form, generates a report, saves settings, or records transaction details, the application writes that information into one or more files. Python makes this process simple through built-in file handling functions.
In this lesson, you will learn how to write data to files using the write() method, understand write mode (w), create new files, overwrite existing files, and explore practical examples from real-world applications.
After completing this lesson, you will be able to:
write() method.w).Programs often need to save information so that it can be used later. Without file writing, data would disappear when the program ends.
Common uses include:
write() MethodThe write() method writes text into a file.
file.write(data)
The method writes the specified string into the file and returns the number of characters written.
Before writing data, the file must be opened in w mode.
file = open("filename.txt", "w")
The w mode performs the following actions:
file = open("student.txt", "w")
file.write("Rahul")
file.close()
print("File Created Successfully")
Output
File Created Successfully
The file student.txt is created, and the text Rahul is written into it.
Rahul
file = open("course.txt", "w")
file.write("Python File Handling")
file.close()
Contents of course.txt
Python File Handling
You can include newline characters (\n) inside the string.
file = open("students.txt", "w")
file.write("Rahul\n")
file.write("Priya\n")
file.write("Amit")
file.close()
Contents of students.txt
Rahul
Priya
Amit
The biggest characteristic of w mode is that it removes all existing data before writing new content.
Suppose student.txt initially contains:
Rahul
Python
92
Now execute:
file = open("student.txt", "w")
file.write("Neha")
file.close()
Contents of student.txt
Neha
All previous data has been removed because the file was opened in write mode.
The write() method accepts only strings. Numbers must be converted before writing.
marks = 95
file = open("marks.txt", "w")
file.write(str(marks))
file.close()
Contents of marks.txt
95
| Application | Purpose |
|---|---|
| School Management | Save student information. |
| Hospital System | Store patient records. |
| Banking Software | Record transactions. |
| Data Analytics | Generate reports. |
| Inventory System | Store product details. |
| Website | Save user feedback. |
file = open("employee.txt", "w")
file.write("Name: Neha\n")
file.write("Department: HR\n")
file.write("Salary: 50000")
file.close()
print("Employee Record Saved")
Output
Employee Record Saved
Contents of employee.txt
Name: Neha
Department: HR
Salary: 50000
Consider the following program.
file = open("sample.txt", "w")
file.write("Hello Python")
file.close()
Execution Steps
Contents of sample.txt
Hello Python
w mode without realizing that existing data will be deleted.\n when writing multiple lines.In this section, you learned how to create files, write text using the write() method, understand write mode (w), overwrite existing files, and save multiple lines of data. You also explored practical examples, execution flow, and common beginner mistakes. In the next section, you will learn how to append data using append mode (a), write multiple lines efficiently using writelines(), compare write() and writelines(), and apply these techniques in real-world Python programs.
In the previous section, you learned how to create files and write data using the write() method. While write mode (w) is useful for creating new files or replacing existing contents, there are many situations where you want to keep the existing data and simply add new information. Python provides append mode (a) for this purpose.
In this section, you will learn how to append data to files, write multiple lines using the writelines() method, compare write() and writelines(), and apply these techniques in practical Python programs.
a)The append mode opens a file for writing without deleting its existing contents. Any new data is added to the end of the file.
file = open("filename.txt", "a")
If the file does not exist, Python automatically creates it.
Suppose student.txt contains:
Rahul
Python
Python program:
file = open("student.txt", "a")
file.write("92")
file.close()
Contents of student.txt
Rahul
Python
92
The existing data remains unchanged, and the new data is added at the end.
Use newline characters (\n) to add multiple lines.
file = open("students.txt", "a")
file.write("\nPriya")
file.write("\nAmit")
file.close()
Contents of students.txt
Rahul
Priya
Amit
writelines() MethodThe writelines() method writes multiple strings from an iterable, such as a list, into a file.
file.writelines(iterable)
Unlike write(), this method expects a collection of strings.
students = [
"Rahul\n",
"Priya\n",
"Amit\n"
]
file = open("students.txt", "w")
file.writelines(students)
file.close()
Contents of students.txt
Rahul
Priya
Amit
writelines()The writelines() method does not automatically insert newline characters. If you want each value to appear on a new line, include \n in each string.
names = [
"Rahul",
"Priya",
"Amit"
]
file = open("names.txt", "w")
file.writelines(names)
file.close()
Contents of names.txt
RahulPriyaAmit
names = [
"Rahul\n",
"Priya\n",
"Amit\n"
]
file = open("names.txt", "w")
file.writelines(names)
file.close()
Contents of names.txt
Rahul
Priya
Amit
write() and writelines()| Feature | write() |
writelines() |
|---|---|---|
| Writes | Single string | Multiple strings |
| Input | String | Iterable of strings |
| Automatic New Line | No | No |
| Common Use | Writing one value | Writing many lines |
students = [
"Rahul\n",
"Priya\n",
"Amit\n"
]
file = open("students.txt", "w")
file.writelines(students)
file.close()
print("Student Records Saved")
Output
Student Records Saved
file = open("log.txt", "a")
file.write("Application Started\n")
file.close()
Each time the program runs, a new log entry is added without removing previous records.
products = [
"Laptop\n",
"Mouse\n",
"Keyboard\n"
]
file = open("products.txt", "w")
file.writelines(products)
file.close()
Contents of products.txt
Laptop
Mouse
Keyboard
w mode only when replacing existing data is acceptable.a mode when existing information should be preserved.writelines() when writing multiple strings.\n manually when each value should appear on a new line.Consider the following program.
file = open("notes.txt", "a")
file.write("Python File Handling\n")
file.close()
Execution Steps
Contents of notes.txt
Existing Notes
Python File Handling
w mode instead of a mode and accidentally deleting existing data.\n when writing multiple lines.write() without converting them to strings.writelines() automatically inserts line breaks.In this section, you learned how to append data using append mode (a), write multiple lines using the writelines() method, and understand the differences between write() and writelines(). You also explored practical examples, best practices, execution flow, and common beginner mistakes. In the next section, you will learn how to write user input to files, generate reports, write binary files, handle writing errors, improve performance, and apply advanced file writing techniques in real-world applications.
In the previous section, you learned how to write data using the write() method, append new information using append mode (a), and write multiple strings using the writelines() method. In real-world applications, however, data is often entered by users, generated automatically, or collected from other systems before being written to files. Python also supports writing binary files and handling errors that may occur during file operations.
In this section, you will learn how to write user input to files, generate reports, write binary files, handle file writing errors, improve performance, and explore practical real-world applications.
Many applications collect information from users and save it for future use.
name = input("Enter your name: ")
file = open("users.txt", "a")
file.write(name + "\n")
file.close()
print("Record Saved Successfully")
Sample Output
Enter your name: Rahul
Record Saved Successfully
Contents of users.txt
Rahul
file = open("students.txt", "a")
for i in range(3):
name = input("Enter Student Name: ")
file.write(name + "\n")
file.close()
print("All Records Saved")
Sample Output
Enter Student Name: Rahul
Enter Student Name: Priya
Enter Student Name: Amit
All Records Saved
Python programs often generate reports and save them into text files.
file = open("report.txt", "w")
file.write("Monthly Sales Report\n")
file.write("--------------------\n")
file.write("Total Sales : 150\n")
file.write("Revenue : ₹450000\n")
file.close()
Contents of report.txt
Monthly Sales Report
--------------------
Total Sales : 150
Revenue : ₹450000
When writing large amounts of data, avoid opening and closing the file repeatedly. Open the file once, write all data, and then close it.
file = open("numbers.txt", "w")
for number in range(1, 101):
file.write(str(number) + "\n")
file.close()
This program writes the numbers 1 to 100 into a file efficiently.
Binary files such as images, audio files, PDFs, and videos must be written using binary mode.
data = b"Python"
file = open("sample.bin", "wb")
file.write(data)
file.close()
Result
A binary file named sample.bin is created containing the byte data.
Sometimes writing to a file may fail due to invalid paths, insufficient permissions, or storage issues. Python’s try and except statements can handle such errors gracefully.
try:
file = open("student.txt", "w")
file.write("Python File Handling")
file.close()
print("File Saved Successfully")
except Exception as error:
print("Error:", error)
Output
File Saved Successfully
If an error occurs, Python displays the error message instead of terminating the program abruptly.
writelines() for writing collections of strings.| Application | Purpose |
|---|---|
| Student Management | Save admission records. |
| Employee Management | Store employee details. |
| Banking Software | Save transaction history. |
| Inventory System | Generate stock reports. |
| Website | Store contact form submissions. |
| Data Analytics | Export processed results. |
file = open("employees.txt", "w")
employees = [
"Rahul\n",
"Neha\n",
"Priya\n"
]
file.writelines(employees)
file.close()
print("Employee List Saved")
Output
Employee List Saved
Contents of employees.txt
Rahul
Neha
Priya
Consider the following program.
name = input("Enter Name: ")
file = open("users.txt", "a")
file.write(name + "\n")
file.close()
Execution Steps
Sample Output
Enter Name: Rahul
Contents of users.txt
Rahul
w) instead of append mode (a) for adding new records.str().In this section, you learned how to write user input to files, generate reports, efficiently write large amounts of data, create binary files, and handle writing errors using try and except. You also explored performance tips, practical applications, execution flow, and common beginner mistakes. In the final section, you will review the complete lesson through a lesson summary, key takeaways, FAQs, coding exercises, interview questions, a mini project, and a preview of the next lesson on Working with CSV and JSON Files.
In this lesson, you learned how to write and append data to files in Python. Writing files allows programs to permanently store information such as user records, reports, logs, transaction details, and application settings. It is one of the most frequently used operations in real-world software development.
You began by understanding the importance of writing files and learned how to create new files using write mode (w). You explored the write() method, learned how to write single and multiple lines, and understood how write mode overwrites existing file contents.
Next, you learned how to preserve existing data using append mode (a). You explored the writelines() method, compared it with write(), and learned how to efficiently write multiple strings into a file.
Finally, you learned how to write user input into files, generate reports, write binary files, handle writing errors using try and except, and improve file writing performance using best practices.
These skills are essential for developing applications that need to save information permanently, including management systems, websites, desktop applications, automation scripts, and data analytics projects.
write() to write a single string into a file.w mode to create or overwrite files.a mode to preserve existing data while adding new information.writelines() to write multiple strings.\n manually when writing multiple lines.wb mode for writing binary files.try and except to handle writing errors.The w mode is used to write data into a file.
w mode?All existing contents are removed before new data is written.
The a (append) mode.
write() and writelines()?write() writes a single string, whereas writelines() writes multiple strings from an iterable.
writelines() automatically add new lines?No. You must include \n manually.
write()?No. Numbers should first be converted into strings using str().
The wb mode.
Closing a file saves all changes and releases system resources.
It allows new information to be added without deleting existing data.
By using try and except statements.
writelines() to save a list of student names.wb mode.try and except.write() method?w mode and a mode.writelines() differ from write()?Create a Python program that stores student records in a text file.
Your program should:
try and except.========== STUDENT RECORD WRITER ==========
Enter Student Name : Rahul
Enter Course : Python
Enter Marks : 92
Record Saved Successfully
------------------------------------------
Enter Student Name : Priya
Enter Course : Data Analytics
Enter Marks : 95
Record Saved Successfully
==========================================
Congratulations! You have learned how to create files, write data, append new information, write multiple lines, generate reports, save user input, write binary files, and handle writing errors in Python. These skills enable you to build applications that permanently store and manage data.
In the next lesson, you will learn Working with CSV and JSON Files: Complete Guide for Beginners. You will explore Python’s csv and json modules, learn how to read and write structured data, and understand how CSV and JSON files are widely used in data analytics, APIs, web development, and data exchange.