Writing text files allows you to store data permanently in a file.
It is useful for saving reports, logs, user data, and program results.
Python provides simple methods to create and write data into text files.
OPENING A FILE FOR WRITING
To write into a file, use the open() function with write mode.
file = open("example.txt", "w")
• "w" → Write mode (creates a new file or overwrites existing file)
After writing, always close the file.
file.write("Hello Python")
file.close()
USING WITH STATEMENT (BEST PRACTICE)
The with statement automatically closes the file after writing.
with open("example.txt", "w") as file:
file.write("Welcome to Python programming.")
This is the recommended way to handle files.
WRITING MULTIPLE LINES
with open("example.txt", "w") as file:
file.write("Line 1\n")
file.write("Line 2\n")
file.write("Line 3\n")
\n adds a new line.
APPEND MODE
If you don’t want to overwrite the file, use append mode "a".
with open("example.txt", "a") as file:
file.write("This line is added later.\n")
Append mode adds content at the end of the file.
WRITING A LIST TO A FILE
lines = ["Apple\n", "Banana\n", "Mango\n"]with open("fruits.txt", "w") as file:
file.writelines(lines)
writelines() writes multiple lines at once.
FILE MODES SUMMARY
• "w" → Write (overwrite file)
• "a" → Append (add to file)
• "x" → Create new file (error if exists)
• "r+" → Read and write
HANDLING ERRORS
try:
with open("example.txt", "w") as file:
file.write("Data saved successfully.")
except Exception as e:
print("An error occurred:", e)
IMPORTANT POINTS
• Write mode overwrites existing content
• Append mode keeps old content
• Always use with for safe file handling
• Use \n for new lines
WHY WRITING FILES IS IMPORTANT
• Save program output
• Store user data
• Create reports and logs
• Essential for automation and data processing
Understanding how to write text files is a key skill for building practical Python applications.