Python Read File into List (5 Easy Ways)

For a Python read file into list, open the file and call f.read().splitlines(). You get one list item per line, without the newline characters that readlines() leaves behind:

with open("cities.txt", encoding="utf-8") as f:
    lines = f.read().splitlines()

The sample files are tiny text and CSV files I created for this, and every example ran on Python 3.12.5.

You’ll see readlines() versus splitlines(), cleaning and skipping blank lines, turning lines into numbers, reading CSV rows into lists or dicts, a pathlib one-liner, and handling bad data.

readlines() vs read().splitlines()

Both give you a list of lines. The difference is the trailing \n: readlines() keeps it, splitlines() removes it:

with open("cities.txt", encoding="utf-8") as f:
    raw = f.readlines()                    # keeps the newline at the end of each line
print(raw)

with open("cities.txt", encoding="utf-8") as f:
    lines = f.read().splitlines()          # no newline characters
print(lines)

Output:

['Austin\n', 'Denver\n', '\n', 'Boston  \n', 'Tampa\n']
['Austin', 'Denver', '', 'Boston  ', 'Tampa']
Command Prompt output comparing Python readlines, which keeps newline characters, with read().splitlines(), which removes them
Note the blank line and the trailing spaces on Boston; both methods keep them as-is.

If you keep the newlines, they’re a common source of bugs, like "Austin\n" == "Austin" being False. More on reading line by line in reading a file line by line.

Cleaning lines and skipping blanks

You can strip each line and drop empty ones in one pass with a list comprehension over the file object; it’s what I use most. Convert at the same time if the lines are numbers:

with open("cities.txt", encoding="utf-8") as f:
    cities = [line.strip() for line in f if line.strip()]    # trim spaces, drop blank lines
print(cities)

with open("prices.txt", encoding="utf-8") as f:
    prices = [float(line) for line in f if line.strip()]
print(prices, f"total ${sum(prices):.2f}")

Output:

['Austin', 'Denver', 'Boston', 'Tampa']
[19.99, 4.5, 102.0, 12.75] total $139.24
Command Prompt output of Python list comprehensions reading a file into a clean list of cities and a list of float prices with a total
Spaces trimmed, blank line gone, and the prices are real numbers you can add up.

Looping over f directly reads one line at a time, which keeps memory low on big files. The with block closes the file afterward; see Python with open() as file.

Reading a CSV file into a list

For comma-separated data, I’d let the csv module handle quoting and commas inside fields. reader gives a list of lists; DictReader gives dicts keyed by the header:

import csv

with open("orders.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.reader(f))                 # list of lists, header included
print(rows)

with open("orders.csv", newline="", encoding="utf-8") as f:
    orders = list(csv.DictReader(f))           # list of dicts keyed by the header
print(orders[0])
print(f"Denver order total: ${float(orders[1]['total']):.2f}")

Output:

[['order_id', 'city', 'total'], ['1001', 'Austin', '59.99'], ['1002', 'Denver', '120.00'], ['1003', 'Boston', '35.50']]
{'order_id': '1001', 'city': 'Austin', 'total': '59.99'}
Denver order total: $120.00
Command Prompt output of Python csv.reader returning a list of lists and csv.DictReader returning dictionaries from an orders CSV
Everything comes in as text, so convert totals with float() before doing math.

A list of lists is easy to work with afterward; see list of lists in Python. For bigger data, pandas’ read_csv() is the next step.

Read a file into a list with pathlib

Path.read_text() opens, reads and closes the file in one call. Choose split() for words or splitlines() for lines:

from pathlib import Path

cities = Path("cities.txt").read_text(encoding="utf-8").split()     # splits on any whitespace
print(cities)

words = Path("cities.txt").read_text(encoding="utf-8").splitlines()
print(words)

Output:

['Austin', 'Denver', 'Boston', 'Tampa']
['Austin', 'Denver', '', 'Boston  ', 'Tampa']

You’ll want to be careful with split(): it also splits on spaces inside a line, which matters for values like “New York”.

How do you handle bad lines when reading a file into a list?

Your real files will contain surprises, and that’s normal. Wrap the conversion in try/except so one bad value doesn’t stop the whole read, and report which line it was:

prices = []
with open("bad_prices.txt", encoding="utf-8") as f:
    for line_no, line in enumerate(f, start=1):
        try:
            prices.append(float(line))
        except ValueError:
            print(f"line {line_no}: skipped {line.strip()!r}")
print(prices)

try:
    open("missing.txt")
except FileNotFoundError as err:
    print("FileNotFoundError:", err.filename)

Output:

line 2: skipped 'N/A'
[19.99, 4.5]
FileNotFoundError: missing.txt
Command Prompt output of Python skipping a non-numeric line while reading prices into a list, and a FileNotFoundError
Line 2 held “N/A”, so it’s skipped with a message; the valid prices are kept.

enumerate(f, start=1) gives human-friendly line numbers; see what enumerate does in Python.

Ways to read a file into a list

You wantUse
Lines without newlinesf.read().splitlines()
Lines with newlinesf.readlines()
Cleaned, non-blank lines[l.strip() for l in f if l.strip()]
Numbers[float(l) for l in f if l.strip()]
CSV rowslist(csv.reader(f)) or list(csv.DictReader(f))
Quick one-linerPath("x.txt").read_text().splitlines()

More file handling guides:

Frequently asked questions

How do I read a file into a list in Python?

Use with open("file.txt") as f: lines = f.read().splitlines(). Each line becomes one list item.

How do I remove the newline characters?

Use splitlines() instead of readlines(), or strip each line: [line.rstrip("\n") for line in f].

How do I skip empty lines?

Filter them in a comprehension: [line.strip() for line in f if line.strip()].

How do I read numbers from a file into a list?

Convert as you read: [float(line) for line in f if line.strip()], with try/except for bad values.

How do I read a CSV into a list of lists?

Use list(csv.reader(f)), opening the file with newline="".

Where are file methods documented?

See Methods of File Objects in the Python tutorial.