How to Write a List to a File in Python

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
VS Code running a Python script that writes a list of four store cities to stores.txt with join
The file holds the four cities, each followed by a newline, so it reads back as four lines.

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']
VS Code output of a Python for loop writing a numbered store list and print with file= writing one city per line
Both files come back as four lines: one with numbers in front, one with just the city names.

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'
VS Code output comparing Python writelines on a plain list, which runs the cities together, with a generator that adds newlines
bad.txt holds AustinDenverBostonSeattle with no breaks; good.txt has a newline after each city.

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
VS Code output of a Python TypeError from writelines on a list of floats, then sales written with two decimals
writelines() raises TypeError for the first float; the f-string version writes each amount with two decimals.

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)]
VS Code output of a Python list saved with json.dump and loaded back equal, a date TypeError, and pickle restoring dates
The JSON round trip returns an equal list, JSON refuses date objects, and pickle restores both dates.

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:

ProblemCauseFix
All items on one linewritelines() adds no newlines"\n".join(items) or add \n
TypeError: write() argument must be strNumbers in the liststr(x) or f"{x:.2f}"
Brackets and quotes in the filef.write(str(items))Join the items, or use JSON
Old contents goneMode "w" truncatesMode "a" to append
UnicodeEncodeError on WindowsDefault locale encodingPass encoding="utf-8"

Once the list is saved, these guides cover the related jobs:

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.