How to Read a File into an Array in Python

To read a file into an array in Python, open it with open() and call read().splitlines(): you get a list with one string per line. For numeric data, numpy.loadtxt() loads the file straight into a NumPy array:

with open("stores.txt", encoding="utf-8") as f:
    stores = f.read().splitlines()      # ['Austin', 'Denver', ...]

import numpy as np
sales = np.loadtxt("sales.csv", delimiter=",", skiprows=1)

Python calls this growable array a list, so that’s what the first version returns. All the output below came from Python 3.12.5 with NumPy 2.5.3, run in Command Prompt on Windows.

In this tutorial, I’ll show you how to read a file into an array in Python as lines, as numbers, as a 2D grid, and as a NumPy array, using one small sales file for four US stores.

Read a file into an array of lines

Here’s the store list. It has a blank line and a trailing space on Denver, like most real exports:

with open("stores.txt", encoding="utf-8") as f:
    raw = f.readlines()
print(raw)                          # newlines are still attached

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

stores = [s.strip() for s in stores if s.strip()]
print(stores, len(stores))

Output:

['Austin\n', 'Denver  \n', 'Seattle\n', '\n', 'Boston\n']
['Austin', 'Denver  ', 'Seattle', '', 'Boston']
['Austin', 'Denver', 'Seattle', 'Boston'] 4
Command Prompt output of Python reading stores.txt into an array with readlines and splitlines, then stripping blank lines
readlines() keeps the \n on every item; splitlines() drops it, and the strip filter leaves four clean store names.

I use splitlines() because it never leaves a newline behind. If you only need a plain list and want more cleanup options, my guide to reading a file into a list in Python goes deeper.

Read numbers from a file into an array

Every line comes back as a string, so convert as you read. Same sales file, now taking only the week 1 column:

from array import array

sales = []
with open("weekly_sales.csv", encoding="utf-8") as f:
    next(f)                              # skip the header row
    for line in f:
        sales.append(float(line.split(",")[1]))
print(sales)
print(f"Week 1 total: ${sum(sales):,.2f}")

typed = array("d", sales)                # typed array of C doubles
print(typed, typed.itemsize, "bytes per item")

Output:

[1249.5, 980.25, 1530.0, 1102.75]
Week 1 total: $4,862.50
array('d', [1249.5, 980.25, 1530.0, 1102.75]) 8 bytes per item

The four week 1 values add up to $4,862.50. The array("d", ...) version stores plain 8-byte floats instead of Python objects, which saves memory on long numeric files.

For very large files, loop over the file object instead of reading it all at once; reading a file line by line in Python explains why that keeps memory flat.

How do you read a file into a 2D array?

A 2D array in plain Python is a list of lists: one inner list per row. The csv module splits each line for you and handles quoted commas:

import csv

with open("weekly_sales.csv", newline="", encoding="utf-8") as f:
    rows = list(csv.reader(f))

header, data = rows[0], rows[1:]
print(header)
print(data[0])

grid = [[float(x) for x in row[1:]] for row in data]
print(grid)
print("Seattle, week 2:", grid[2][1])
print(f"Austin total: ${sum(grid[0]):,.2f}")

Output:

['store', 'week1', 'week2', 'week3']
['Austin', '1249.50', '1310.00', '1187.25']
[[1249.5, 1310.0, 1187.25], [980.25, 1045.5, 1102.0], [1530.0, 1488.75, 1602.4], [1102.75, 1150.0, 1098.6]]
Seattle, week 2: 1488.75
Austin total: $3,746.75
Command Prompt output of Python reading weekly_sales.csv into a 2D array with csv.reader and indexing one cell
The header stays separate, the numbers become a 4 x 3 grid of floats, and grid[2][1] picks Seattle’s week 2 value.

Austin’s three weeks total $3,746.75. Building and indexing these nested lists is covered in initializing a 2D array in Python.

Read a file into a NumPy array with loadtxt()

When the data is numeric, NumPy does the splitting and converting in one call. Same CSV, loaded with loadtxt():

import numpy as np

sales = np.loadtxt("weekly_sales.csv", delimiter=",",
                   skiprows=1, usecols=(1, 2, 3))
print(sales.shape, sales.dtype)
print(sales)
print("Per store:", sales.sum(axis=1))
print("Per week: ", sales.sum(axis=0))

stores = np.loadtxt("weekly_sales.csv", delimiter=",",
                    skiprows=1, usecols=0, dtype=str)
print(stores)

Output:

(4, 3) float64
[[1249.5  1310.   1187.25]
 [ 980.25 1045.5  1102.  ]
 [1530.   1488.75 1602.4 ]
 [1102.75 1150.   1098.6 ]]
Per store: [3746.75 3127.75 4621.15 3351.35]
Per week:  [4862.5  4994.25 4990.25]
['Austin' 'Denver' 'Seattle' 'Boston']
Command Prompt output of numpy loadtxt reading weekly_sales.csv into a 4 by 3 float array with per-store and per-week totals
loadtxt() returns a (4, 3) float64 array, so row and column totals are one sum() call each.

Seattle leads with $4,621.15 over three weeks. skiprows=1 skips the header and usecols picks columns by index. You load the store names with a second call and dtype=str, since one array holds one type.

For more on shapes and axes, see working with a NumPy 2D array. Full CSV options are in reading a CSV file with NumPy.

Fix loadtxt errors with missing values and headers

Two errors account for most failed loads: forgetting the header row, and a blank cell. Here, Denver’s week 2 sale is missing in a copy of the file:

import numpy as np

try:
    np.loadtxt("weekly_sales.csv", delimiter=",", usecols=(1, 2, 3))
except ValueError as err:
    print("No skiprows:", err)

try:
    np.loadtxt("weekly_sales_gaps.csv", delimiter=",",
               skiprows=1, usecols=(1, 2, 3))
except ValueError as err:
    print("Blank field:", err)

sales = np.genfromtxt("weekly_sales_gaps.csv", delimiter=",",
                      skip_header=1, usecols=(1, 2, 3))
print(sales)
print("Week means:", np.nanmean(sales, axis=0).round(2))

Output:

No skiprows: could not convert string 'week1' to float64 at row 0, column 2.
Blank field: could not convert string '' to float64 at row 1, column 3.
[[1249.5  1310.   1187.25]
 [ 980.25     nan 1102.  ]
 [1530.   1488.75 1602.4 ]
 [1102.75 1150.   1098.6 ]]
Week means: [1215.62 1316.25 1247.56]
Command Prompt output of numpy loadtxt ValueError on a header and a blank field, then genfromtxt filling the gap with nan
Both loadtxt() calls stop with a ValueError; genfromtxt() loads the same file and puts nan in the empty cell.

The week 2 mean of $1,316.25 comes from the three stores you still have data for.

Note: genfromtxt() uses skip_header, not skiprows. Use np.nanmean() or np.nansum() so one gap doesn’t turn a whole total into nan; NumPy genfromtxt in Python covers fill values.

Pick up from here with these file and array guides:

Frequently asked questions

How do I read a text file into an array in Python?

Use open(path).read().splitlines() for a list of lines, or numpy.loadtxt(path) for numbers.

What’s the difference between readlines() and splitlines()?

readlines() keeps the newline at the end of each item. read().splitlines() removes it.

How do I read a CSV file into a 2D array?

Use list(csv.reader(f)) for a list of lists, or np.loadtxt(path, delimiter=",", skiprows=1) for numbers.

Why does numpy loadtxt raise ValueError: could not convert string to float?

Usually a header row or a blank cell. Add skiprows=1, or switch to np.genfromtxt() for missing values.

Do I need the array module to read numbers from a file?

No. A list works for most jobs. array.array only helps when memory matters on large numeric files.

Where is numpy.loadtxt documented?

See numpy.loadtxt in the NumPy docs.