Writing Files
-
This lesson explains how to create files and write or append data using Python.
What is Writing to a File?
Writing to a file means storing data permanently in a file instead of printing it on the screen.
Python allows us to:
Create new files
Write text into files
Add new data to existing files
File Modes Used for Writing
1️.Writing Text to a File (w mode)
What is w Mode?
Opens file for writing
Creates a new file if it does not exist
Deletes old content if file already exists
Use carefully, as data can be lost.
Syntax
file = open("filename.txt", "w")
file.write("text")
file.close()
Writing Text Using Write Mode
This program writes text into a file. If the file exists, its content is replaced.
file = open("notes.txt", "w")
file.write("Welcome to Python File Handling")
file.close()
Writing Multiple Lines to File
This program writes multiple lines using newline characters.
file = open("notes.txt", "w")
file.write("Python\n")
file.write("File Handling\n")
file.write("Write Mode Example")
file.close()
Using writelines() Method
This program writes a list of strings into a file.
lines = ["Python\n", "Java\n", "C++\n"]
file = open("languages.txt", "w")
file.writelines(lines)
file.close()
2.Appending Text to a File (a mode)
What is a Mode?
Opens file for adding data
Data is added at the end of file
Existing content is not removed
Creates file if it does not exist
Syntax
file = open("filename.txt", "a")
file.write("new text")
file.close()
Appending Text Using Append Mode
This program adds new content at the end of the file.
file = open("notes.txt", "a")
file.write("\nThis line is appended")
file.close()
Appending Multiple Lines to File
This program appends several lines to an existing file.
file = open("notes.txt", "a")
file.write("\nLine 1")
file.write("\nLine 2")
file.close()
Using with Statement (Best Practice)
Why Use with?
Automatically closes the file
Prevents file corruption
Cleaner and safer code
Using with Statement for Writing
This program writes text using with, without manually closing the file.
with open("data.txt", "w") as file:
file.write("Python is easy to learn")
Appending Text Using with Statement
This program appends text safely using with.
with open("data.txt", "a") as file:
file.write("\nAppended line")
Difference Between w and a