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

ModeDescription
"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 file
  • writelines() β†’ writes multiple lines
  • with open() β†’ best practice for file handling