A regional manager asked me to write a Python list of store cities to a file each night, one city per line, so a scheduling tool could pick it up. My first try with writelines() gave her one long word: AustinDenverBostonSeattle.
Quick answer: open the file in "w" mode and write "\n".join(items). Convert numbers with str() first, and use json.dump() when you need the list back exactly.
stores = ["Austin", "Denver", "Boston", "Seattle"]
with open("stores.txt", "w", encoding="utf-8") as f:
f.write("\n".join(stores) + "\n")
In this tutorial, I’ll show you how to write a list to a file in Python with join(), a loop, writelines(), pathlib, append mode, CSV rows, JSON and pickle, plus the errors that trip people up.
I ran each script below with Python 3.12.5 in VS Code, and every output block is copied from those runs.
How do you write a list to a file in Python with join()?
join() glues the items into one string with a newline between them, and one write() call saves it. I add a final \n so the last line ends properly too:
stores = ["Austin", "Denver", "Boston", "Seattle"]
with open("stores.txt", "w", encoding="utf-8") as f:
f.write("\n".join(stores) + "\n")
with open("stores.txt", encoding="utf-8") as f:
text = f.read()
print(repr(text))
print(len(text.splitlines()), "lines written")
Output:
'Austin\nDenver\nBoston\nSeattle\n'
4 lines written

join() only accepts strings, so this is the right tool for names, IDs and other text. The file modes and encodings behind open() are covered in writing a string to a file in Python.
Write each list item on a new line with a for loop
A loop is handy when each line needs extra formatting, like a number in front. You can also pass file=f to print(), which adds the newline for you:
stores = ["Austin", "Denver", "Boston", "Seattle"]
with open("numbered.txt", "w", encoding="utf-8") as f:
for n, store in enumerate(stores, start=1):
f.write(f"{n}. {store}\n")
with open("printed.txt", "w", encoding="utf-8") as f:
for store in stores:
print(store, file=f) # print() adds the newline
for name in ["numbered.txt", "printed.txt"]:
with open(name, encoding="utf-8") as f:
print(name, "->", f.read().splitlines())
Output:
numbered.txt -> ['1. Austin', '2. Denver', '3. Boston', '4. Seattle']
printed.txt -> ['Austin', 'Denver', 'Boston', 'Seattle']

I use the loop when lines need numbering or padding, and join() for everything else. For writing loose strings rather than a list, see writing multiple lines to a file in Python.
Why does writelines() put the whole list on one line?
The name suggests it writes lines, but writelines() just writes each string as it is. It never adds a newline, which is exactly what bit me on that store export:
stores = ["Austin", "Denver", "Boston", "Seattle"]
with open("bad.txt", "w", encoding="utf-8") as f:
f.writelines(stores) # no newlines added
with open("good.txt", "w", encoding="utf-8") as f:
f.writelines(f"{s}\n" for s in stores) # add them yourself
for name in ["bad.txt", "good.txt"]:
with open(name, encoding="utf-8") as f:
print(f"{name:<9}{f.read()!r}")
Output:
bad.txt 'AustinDenverBostonSeattle'
good.txt 'Austin\nDenver\nBoston\nSeattle\n'

A generator expression adds the \n without building a second list in memory. If you actually want everything on one line, writing to a file without a newline shows the cleaner options.
Write a list of numbers or prices to a file
Same stores, now with their daily sales. write() and writelines() only take strings, so a list of floats fails straight away:
sales = [1249.5, 980, 2310.75, 645.2]
try:
with open("sales.txt", "w", encoding="utf-8") as f:
f.writelines(sales)
except TypeError as err:
print("TypeError:", err)
with open("sales.txt", "w", encoding="utf-8") as f:
f.write("\n".join(f"{amt:.2f}" for amt in sales) + "\n")
with open("sales.txt", encoding="utf-8") as f:
print(f.read())
Output:
TypeError: write() argument must be str, not float
1249.50
980.00
2310.75
645.20

The :.2f format also turns 980 into 980.00, so dollar amounts line up. More formatting choices are in printing 2 decimal places in Python.
Append a list to an existing file instead of overwriting it
Mode "w" empties the file every time you open it. To add tomorrow’s new stores below the existing ones, open it with "a":
stores = ["Austin", "Denver", "Boston", "Seattle"]
new_stores = ["Phoenix", "Miami"]
with open("stores.txt", "w", encoding="utf-8") as f: # "w" replaces
f.write("\n".join(stores) + "\n")
with open("stores.txt", "a", encoding="utf-8") as f: # "a" adds
f.write("\n".join(new_stores) + "\n")
with open("stores.txt", encoding="utf-8") as f:
print(f.read().splitlines())
Output:
['Austin', 'Denver', 'Boston', 'Seattle', 'Phoenix', 'Miami']
The file now lists six cities, with Phoenix and Miami after the original four. If you need the opposite, replacing a file’s contents on purpose, read overwriting a file in Python.
Save a list of lists as rows with tabs or the csv module
A list of lists is a table, so each inner list becomes one row. A tab-joined line works for simple data, but the csv module handles quoting for you:
import csv
rows = [["store", "state", "sales"],
["Austin", "TX", 1249.50],
["Denver", "CO", 980.00],
["Boston", "MA", 2310.75]]
with open("sales.tsv", "w", encoding="utf-8") as f:
for row in rows:
f.write("\t".join(str(v) for v in row) + "\n")
with open("sales.csv", "w", newline="", encoding="utf-8") as f:
csv.writer(f).writerows(rows)
with open("sales.csv", encoding="utf-8") as f:
print(f.read())
Output:
store,state,sales
Austin,TX,1249.5
Denver,CO,980.0
Boston,MA,2310.75
Notice that 1249.50 is written as 1249.5 and 980.00 as 980.0, because Python stores the float, not your typing. Format the numbers first if the file must show cents. Headers, DictWriter and pandas are in writing a list to CSV in Python.
Note: pass newline="" to open() with the csv module, or Windows adds a blank line between rows.
Save a list with JSON or pickle so it loads back the same
A text file turns every item into a string, so 3 and True come back as "3" and "True". JSON keeps numbers, booleans and None; pickle keeps almost any Python object:
import json
import pickle
from datetime import date
order = ["Austin", 3, 1249.5, True, None]
with open("order.json", "w", encoding="utf-8") as f:
json.dump(order, f)
with open("order.json", encoding="utf-8") as f:
print("file :", f.read())
with open("order.json", encoding="utf-8") as f:
back = json.load(f)
print("json :", back, back == order)
shipped = [date(2026, 3, 2), date(2026, 3, 9)]
try:
json.dumps(shipped)
except TypeError as err:
print("json :", err)
with open("shipped.pkl", "wb") as f:
pickle.dump(shipped, f)
with open("shipped.pkl", "rb") as f:
print("pickle:", pickle.load(f))
Output:
file : ["Austin", 3, 1249.5, true, null]
json : ['Austin', 3, 1249.5, True, None] True
json : Object of type date is not JSON serializable
pickle: [datetime.date(2026, 3, 2), datetime.date(2026, 3, 9)]

JSON is readable and works with other languages, so I default to it. Its options, like indent, are in writing JSON data to a file in Python.
Important: only call pickle.load() on files you created yourself, because a crafted pickle file can run code when it loads.
Write a list to a file with pathlib in one line
Path.write_text() opens, writes and closes the file in one call, which is neat for small lists:
from pathlib import Path
stores = ["Austin", "Denver", "Boston", "Seattle"]
path = Path("stores.txt")
path.write_text("\n".join(stores) + "\n", encoding="utf-8")
print(path.read_text(encoding="utf-8").splitlines())
print(path.stat().st_size, "bytes on disk")
Output:
['Austin', 'Denver', 'Boston', 'Seattle']
33 bytes on disk
Four short names take 33 bytes because Windows text mode saves each \n as two characters (\r\n). To load the lines again, see reading a file into a list in Python.
Common errors when writing a list to a file
The mistake I see most often is writing the list itself with str(). You get the brackets and quotes in the file, which nothing else can read cleanly:
stores = ["Austin", "Denver", "Boston", "Seattle"]
with open("brackets.txt", "w", encoding="utf-8") as f:
f.write(str(stores))
with open("brackets.txt", encoding="utf-8") as f:
print(f.read())
Output:
['Austin', 'Denver', 'Boston', 'Seattle']
Here are the problems I run into most, with the fix for each:
| Problem | Cause | Fix |
|---|---|---|
| All items on one line | writelines() adds no newlines | "\n".join(items) or add \n |
TypeError: write() argument must be str | Numbers in the list | str(x) or f"{x:.2f}" |
| Brackets and quotes in the file | f.write(str(items)) | Join the items, or use JSON |
| Old contents gone | Mode "w" truncates | Mode "a" to append |
UnicodeEncodeError on Windows | Default locale encoding | Pass encoding="utf-8" |
Once the list is saved, these guides cover the related jobs:
- Save an array to a file in Python
- Write a dictionary to a file in Python
- Create a list in Python
- Save variables to a file in Python
Frequently asked questions
How do I write a list to a file in Python?
Open the file with open("file.txt", "w") and write "\n".join(items). Convert non-string items with str() first.
How do I write each list item on a new line?
Use "\n".join(items), a loop with f.write(f"{item}\n"), or print(item, file=f).
Why does writelines() not add new lines?
writelines() writes each string exactly as given. Add the newline yourself, for example f.writelines(f"{s}\n" for s in items).
How do I save a list and load it back as a list?
Use json.dump(items, f) and json.load(f). For dates or custom objects, use pickle on files you trust.
How do I add a list to the end of an existing file?
Open the file in append mode, open("file.txt", "a"), then write the joined items.
Where is file writing documented in Python?
See Reading and Writing Files in the Python tutorial.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay · Microsoft MVP profile · LinkedIn