
If you’ve just started learning Python and want to store some text data, writing to a .txt
file is one of the simplest yet most practical skills you can master.
TXT files are lightweight, easy to read, and supported by almost every device and platform.
The best part? In Python, creating one is as easy as printing text to the screen, except your output goes into a file.
Why Write TXT Files with Python?
Writing TXT files can be useful for:
Automating data logging – For example, saving the results of a program without copying and pasting them manually.
Storing configuration or output results – A TXT file can store settings or computed data for later use.
Creating reports – Python can process data and output it in plain text format for easy sharing.
Understanding Python File Modes
When opening a file in Python, you choose a mode:
"w"
– Write mode (creates a new file or overwrites an existing one)."a"
– Append mode (adds new text to the end of the file without erasing previous content)."x"
– Exclusive creation mode (fails if the file already exists)."r+"
– Read and write mode (modifies existing files without erasing them).
Basic Example: Writing a TXT File
Here’s a quick example of writing text to a file:
# Create and write to a new text file
file = open("example.txt", "w")
file.write("Hello, this is my first file in Python!")
file.close()
This will create a file named example.txt
in your working directory containing your message.
Writing Multiple Lines
If you want to store multiple lines, you can either loop through a list or use writelines()
.
lines = ["First line\n", "Second line\n", "Third line\n"]
file = open("example.txt", "w")
file.writelines(lines)
file.close()
Notice the \n
at the end of each string — that’s how you create new lines in the file.
Using the with
Statement (Best Practice)
Using the with
statement ensures the file is closed automatically, even if an error occurs.
with open("example.txt", "w") as file:
file.write("This is a safer way to write files.")
This method is cleaner and reduces the risk of leaving files open accidentally.
Adding Data Without Overwriting
If you want to add text to an existing file without erasing its content, use append mode "a"
:
with open("example.txt", "a") as file:
file.write("\nThis line will be added without deleting the old text.")
Handling Encoding Issues
Python defaults to UTF-8 encoding, which works for most cases. However, if you’re dealing with special characters (like emojis or non-English alphabets), specify the encoding explicitly:
with open("example.txt", "w", encoding="utf-8") as file:
file.write("Café ☕ — now with proper encoding!")
Common Mistakes to Avoid
Forgetting to close the file – Always use
with
orfile.close()
.Accidentally overwriting data – Be mindful of the
"w"
mode.Mixing read/write without correct mode – Use
"r+"
for that.
Final Thoughts
Writing TXT files in Python is quick and incredibly useful for automating workflows, logging information, or storing data in a universally accessible format.
Once you’ve mastered the basics, you can explore more advanced file-handling techniques like reading large files in chunks, working with CSVs, or generating files dynamically.
And if you ever need a quick way to create simple text files without coding, you can always try a txt file maker for a fast, browser-based alternative.
Write a comment ...