Writing files allows a Python program to store data in a file. This is useful for saving logs, reports, user data, or program results.
Python uses the built-in open() function to create and write to files.
π Opening a File for Writing
To write to a file, you open it in write mode ("w").
Syntax:
file = open("filename", "w")
"w"β Write mode- If the file does not exist, Python creates it
- If the file already exists, Python overwrites the content
Example:
file = open("data.txt", "w")
file.write("Hello Python")
file.close()
This creates a file data.txt with the text:
Hello Python
π Writing Multiple Lines
You can write multiple lines by calling write() multiple times.
Example:
file = open("data.txt", "w")
file.write("Python Programming\n")
file.write("File Handling Example\n")
file.write("Learning Python\n")file.close()
Output in the file:
Python Programming
File Handling Example
Learning Python
β
Using with open() (Recommended)
The with statement automatically closes the file after writing.
Example:
with open("data.txt", "w") as file:
file.write("Hello World")
Advantages:
β Automatically closes the file
β Cleaner and safer code
π Writing a List of Lines
You can write multiple lines at once using writelines().
Example:
lines = ["Python\n", "Programming\n", "Tutorial\n"]with open("data.txt", "w") as file:
file.writelines(lines)
π File Modes for Writing
| Mode | Description |
|---|---|
"w" | Write (overwrites file) |
"a" | Append (adds content to end of file) |
"x" | Create new file (error if file exists) |
Example of append mode:
with open("data.txt", "a") as file:
file.write("New line added\n")
π Example Program
with open("student.txt", "w") as file:
file.write("Name: Rahul\n")
file.write("Course: Python\n")
file.write("Level: Beginner\n")
The file student.txt will contain:
Name: Rahul
Course: Python
Level: Beginner
π§ Summary
Important functions for writing files:
write()β writes text to a filewritelines()β writes multiple lineswith open()β best practice for file handling