Table of Contents
What Will You Learn
In this tutorial, you'll explore Python's file handling capabilities, focusing on writing to text files. You'll learn how to open files using the open()
function with different modes ('w'
, 'a'
, 'x'
), write data using write()
and writelines()
, and manage file resources efficiently using the with
statement. The guide also covers best practices for handling different file encodings and error management, equipping you with the skills to write and manage text files effectively in Python.
Writing data to a text file is a critical skill for any Python developer. Whether you're saving user input, logs, reports, or configuration data, understanding how to create and modify files is essential. It allows your programs to persist data between runs and communicate with other systems or scripts. Once you master file writing, you can build applications that generate output, store processed results, or log actions in real-time.
Python offers simple, readable tools for writing to text files through the built-in open()
function, supporting various modes like write ("w"
) and
append ("a"
). Combined with the with
statement, this ensures secure and reliable file handling. Learning these techniques early helps you avoid data
loss and maintain cleaner, more maintainable code.
How to Open and Write a Text File in Python?
To write to a text file in Python, use the open()
function with mode "w"
to overwrite or "a"
to append. Always use the
with
statement to ensure the file is closed properly after writing. The .write()
method is used to insert data into the file. You can write strings,
format numbers, or combine variables into structured output. If the file doesn’t exist, it will be created. If it does exist and you use mode "w"
, the file will be
overwritten.
# Write new content (overwrites file)
with open("output.txt", "w") as f:
f.write("This will overwrite the file.\n")
# Append content (preserves existing data)
with open("output.txt", "a") as f:
f.write("This line is added to the end.\n")
These two modes cover most real-world use cases for file writing and logging.
How to Write to a File Without Overwriting?
To avoid overwriting an existing file, use the append mode by passing "a"
to the open()
function. This mode adds new content to the end
of the file instead of replacing its contents. It’s commonly used for logging, adding new records, or writing incremental data. Always confirm that you’re using
"a"
and not "w"
, as the latter will erase all existing data. You can also check if the file exists before writing by using
os.path.exists()
. This adds a layer of safety when generating reports or logs.
# Example 1: Append to an existing file
with open("notes.txt", "a") as f:
f.write("Added on next run.\n")
# Example 2: Only write if file doesn't exist
import os
if not os.path.exists("log.txt"):
with open("log.txt", "w") as f:
f.write("Start of new log.\n")
How to Write Lists, Arrays, and Matrices to a Text File?
Python provides flexible ways to write structured data like lists, arrays, and matrices into text files. The key is to convert the data into strings using loops,
join()
, or string formatting. For one-dimensional data (lists or arrays), each element can go on a new line or be joined into a comma-separated string. For matrices
(2D lists), use nested loops to write each row on a new line. Always open the file using the "w"
or "a"
mode and write with proper formatting.
Whether you're exporting raw values or preparing logs, formatting consistency is key. You can also use libraries like csv
for comma-separated output, but basic text
output is enough for many beginner use cases.
Writing structured data correctly prepares you for real-world tasks like data export, logging, and automation.
Write a List
Writing a list to a file is simple once you convert the list elements into a string format. You can either write all items on one line using join()
, or write each
item on a separate line using a loop. This is useful for exporting simple datasets like names, IDs, or log entries. Always ensure your data is converted to strings before
writing. Use newline characters (\n
) for line breaks.
# Example 1: Write each item on a new line
fruits = ["apple", "banana", "cherry"]
with open("fruits.txt", "w") as f:
for item in fruits:
f.write(item + "\n")
# Example 2: Write all items on one line, comma-separated
fruits = ["apple", "banana", "cherry"]
with open("fruits_line.txt", "w") as f:
f.write(", ".join(fruits))
Write an Array
Arrays are similar to lists but usually contain only numbers. You can use loops or string formatting to convert and write array data. This is helpful when logging numeric results
or exporting calculation outputs. Use str()
or map()
to handle numeric conversion. Format them with commas, spaces, or line breaks based on your output
needs.
# Example 1: Write array values line by line
numbers = [10, 20, 30]
with open("numbers.txt", "w") as f:
for n in numbers:
f.write(str(n) + "\n")
# Example 2: Write array as space-separated string
numbers = [10, 20, 30]
with open("numbers_inline.txt", "w") as f:
f.write(" ".join(map(str, numbers)))
Write a Matrix (Nested List)
A matrix in Python is typically represented as a list of lists. To write it to a file, you’ll need a nested loop or a generator expression that processes each row. Each row is usually written as a separate line, with elements separated by spaces or commas. This is especially useful for numerical data, tables, or CSV-style formats. Proper formatting improves readability and makes the file easier to parse later.
# Example 1: Space-separated rows
matrix = [[1, 2], [3, 4], [5, 6]]
with open("matrix.txt", "w") as f:
for row in matrix:
f.write(" ".join(map(str, row)) + "\n")
# Example 2: Comma-separated CSV-style rows
matrix = [[1, 2, 3], [4, 5, 6]]
with open("matrix_csv.txt", "w") as f:
for row in matrix:
f.write(",".join(map(str, row)) + "\n")
How to Write a Dictionary to a Text File?
To write a dictionary to a text file in Python, you must first convert each key-value pair into a readable string format. The most common approach is to loop through the
dictionary and write each entry as key: value
. This is useful for configuration files, simple databases, or logging structured data. For more complex formats, you
can use modules like json
, but basic text writing is often enough for beginners. Always open the file using "w"
or "a"
depending on whether
you want to overwrite or append data. Format consistency is key to making the file easy to parse later.
# Example 1: Write key-value pairs line by line
user = {"name": "Alice", "age": 30, "city": "London"}
with open("user.txt", "w") as f:
for key, value in user.items():
f.write(f"{key}: {value}\n")
# Example 2: Convert the entire dictionary to a string
settings = {"volume": 75, "brightness": 40}
with open("settings.txt", "w") as f:
f.write(str(settings))
Common Mistakes When Writing to Text Files in Python
Using "w"
Instead of "a"
One of the most common beginner mistakes is using "w"
mode to write to a file when the intention was to add content, not erase it. Mode "w"
clears the
file before writing, which leads to accidental data loss. If you want to keep existing data and add new content, always use "a"
(append mode).
# Wrong
with open("log.txt", "w") as f:
f.write("New entry\n") # Overwrites file
# Correct
with open("log.txt", "a") as f:
f.write("New entry\n") # Appends to file
Forgetting to Convert Data to String
The .write()
method only accepts strings. Trying to write integers, lists, or dictionaries without converting them causes a TypeError
. Always use
str()
or f-strings
to format your data before writing. This ensures that the file content is readable and the program doesn’t crash.
# Wrong
age = 25
with open("info.txt", "w") as f:
f.write(age) # TypeError
# Correct
with open("info.txt", "w") as f:
f.write(str(age))
Not Using with
Statement
Beginners often open files using open()
but forget to close them using .close()
. This can lead to data not being saved properly or file corruption. The
best practice is to use a with
block, which ensures the file is closed automatically, even if an error occurs.
# Wrong
f = open("data.txt", "w")
f.write("Some text")
# f.close() missing
# Correct
with open("data.txt", "w") as f:
f.write("Some text")
Writing Without Newlines
When writing multiple lines to a file, beginners sometimes forget to include newline characters (\n
). As a result, all the content ends up on one line, making the
file unreadable. Always add \n
at the end of each line unless you intend to write a single long line.
# Wrong
with open("log.txt", "w") as f:
f.write("Line 1")
f.write("Line 2")
# Correct
with open("log.txt", "w") as f:
f.write("Line 1\n")
f.write("Line 2\n")
Overwriting During Loop Writes
Some beginners mistakenly open a file inside a loop using mode "w"
, which causes the file to be cleared on every iteration. This results in only the last value being
saved. Always open the file once before the loop starts and write all lines within that block.
# Wrong
for i in range(3):
with open("output.txt", "w") as f:
f.write(f"Item {i}\n") # Overwrites each time
# Correct
with open("output.txt", "w") as f:
for i in range(3):
f.write(f"Item {i}\n")
FAQ — Write to a Text File in Python
How do I write to a text file in Python?
Writing to a text file in Python involves opening the file using the built-in open()
function with write ("w"
) or append ("a"
) mode, then
using the .write()
method to send data to the file. When using "w"
mode, Python will create the file if it doesn't exist or overwrite it if it does.
Use "a"
mode to append data without erasing existing content. The with
statement is highly recommended because it automatically closes the file once
the writing is done, preventing file locks or incomplete saves.
with open("output.txt", "w") as f:
f.write("Hello, file!\n")
This basic pattern works for writing strings, formatted data, or even structured output like CSV lines. Always convert non-string data types using str()
or string
formatting before writing.
How can I write multiple lines to a file in Python?
You can write multiple lines to a file in Python by using a loop with .write()
, or by using the writelines()
method with a list of strings. When using
.write()
, don’t forget to include newline characters (\n
) at the end of each line, or all text will be merged into a single line. The
writelines()
method does not add line breaks automatically, so each string in the list must already include them.
# Method 1: Loop
lines = ["First line\n", "Second line\n"]
with open("file.txt", "w") as f:
for line in lines:
f.write(line)
# Method 2: writelines()
with open("file.txt", "w") as f:
f.writelines(lines)
Choose the method that fits your formatting needs and readability preferences.
How do I prevent overwriting a file when writing?
To prevent overwriting an existing file, use append mode "a"
instead of write mode "w"
. Append mode adds new content to the end of the file while
preserving existing data. If you're unsure whether the file exists, you can use os.path.exists()
from the os
module to check before writing. This
approach is common in logging, audit trails, or history tracking.
import os
if os.path.exists("report.txt"):
with open("report.txt", "a") as f:
f.write("New data added.\n")
else:
with open("report.txt", "w") as f:
f.write("Starting fresh report.\n")
This ensures your important data is never accidentally erased and gives you control over how data is updated.
How do I write numbers or lists to a file in Python?
Python requires data to be in string format before writing it to a file. To write numbers, you need to convert them using str()
or
f-string
formatting. For lists, you can loop through the items and write each one on a new line, or use join()
to create a single line with a
separator like commas. Failing to convert the data will raise a TypeError
.
# Writing numbers
age = 28
with open("data.txt", "w") as f:
f.write(str(age))
# Writing a list
colors = ["red", "blue", "green"]
with open("list.txt", "w") as f:
for color in colors:
f.write(color + "\n")
Always format your data cleanly before writing to keep your files readable and organized.