HOWTO · Python

How to Write an Array to a Text File in Python

This tutorial demonstrates how to write and save an array into a text file in Python.

On this page

Python can write an array’s values to a text file for later inspection, sharing, or numeric loading. Choose ordinary file writing when you control the text layout, a context manager for automatic cleanup, and NumPy’s text functions when you need a defined numeric format that can be loaded again. The examples below use temporary paths so they can be run without leaving files behind.

Write an Array to a Text File with open()

Use open() with mode "w" to create a file or replace its existing contents. This mode is write-only, so reopen the file with mode "r" when you want to verify it. The Python file mode guide describes the other modes, including append mode "a" and read/write mode "w+". Since "w" replaces old contents, use "a" when new text should be added to the end instead.

For a one-dimensional sequence, convert the values to text and choose separators that suit the reader. Run this example:

from pathlib import Path
from tempfile import TemporaryDirectory

values = [23, 22, 24, 25]
rows = [[23, 22, 24, 25], [13, 14, 15, 19]]

with TemporaryDirectory() as folder:
    path = Path(folder) / "sample.txt"
    file = open(path, "w", encoding="utf-8")
    file.write("[" + " ".join(map(str, values)) + "]")
    file.close()

    file = open(path, "r", encoding="utf-8")
    contents = file.read()
    file.close()
    print("Array contents in sample.txt:", contents)

    matrix_path = Path(folder) / "matrix.txt"
    file = open(matrix_path, "w", encoding="utf-8")
    file.write("\n".join(" ".join(map(str, row)) for row in rows))
    file.close()

    file = open(matrix_path, "r", encoding="utf-8")
    matrix_contents = file.read()
    file.close()
    print("Rows in matrix.txt:")
    print(matrix_contents)

This writes a one-dimensional sequence on one line and a two-dimensional sequence as one row per line. Each write() call accepts text, so numeric values must first be converted or formatted as strings. Calling close() flushes pending text and releases the file; the second open is needed because a file opened with "w" cannot be read through that same handle.

Writing str(array) is convenient for a quick display, but its formatting is intended for presentation and can depend on the array type and display settings. Do not treat that representation as a stable interchange format for numeric data.

Write an Array with a Context Manager

A with statement manages the file handle and closes it when the indented block ends, including when work in the block exits early. This keeps the same explicit text layout while avoiding manual close() calls. The example handles both shapes and then reads the files after their writing blocks have ended:

from pathlib import Path
from tempfile import TemporaryDirectory

values = [23, 25, 27, 29, 30]
rows = [[23, 25, 27, 29], [30, 31, 32, 34]]

with TemporaryDirectory() as folder:
    one_dimensional_path = Path(folder) / "values.txt"
    with open(one_dimensional_path, "w", encoding="utf-8") as file:
        file.write(" ".join(map(str, values)))

    two_dimensional_path = Path(folder) / "rows.txt"
    with open(two_dimensional_path, "w", encoding="utf-8") as file:
        file.write("\n".join(" ".join(map(str, row)) for row in rows))

    with open(one_dimensional_path, "r", encoding="utf-8") as file:
        print("Values:", file.read())
    with open(two_dimensional_path, "r", encoding="utf-8") as file:
        print("Rows:")
        print(file.read())

The file closes as each with block finishes, so the later reads happen only after writing is complete. Set encoding="utf-8" when producing text so the encoding is explicit, especially if values include non-ASCII characters. A space-separated or line-separated layout is easy to inspect, but parsing it later requires agreeing on that layout.

Save and Reload Numeric Arrays with NumPy

For numeric data, NumPy provides numpy.savetxt() and numpy.loadtxt() to write and parse a documented text layout. Set the delimiter and numeric format while saving, then pass the same delimiter when loading. Unlike a printed array representation, the resulting delimited rows are designed for numeric interchange. See the numpy.loadtxt() reference for additional loading options.

This example saves both a one-dimensional array and a two-dimensional array. The integer format avoids scientific notation for these values, and the comma delimiter makes columns explicit:

from pathlib import Path
from tempfile import TemporaryDirectory

import numpy as np

values = np.array([23, 24, 25, 26, 28])
matrix = np.array([[23, 24, 25], [34, 45, 46]])

with TemporaryDirectory() as folder:
    values_path = Path(folder) / "values.csv"
    matrix_path = Path(folder) / "matrix.csv"

    np.savetxt(values_path, values, delimiter=",", fmt="%d")
    np.savetxt(matrix_path, matrix, delimiter=",", fmt="%d")

    loaded_values = np.loadtxt(values_path, delimiter=",", dtype=int)
    loaded_matrix = np.loadtxt(matrix_path, delimiter=",", dtype=int)

    print("Values match:", np.array_equal(values, loaded_values))
    print("Matrix matches:", np.array_equal(matrix, loaded_matrix))

Use a format that preserves the precision you need; "%d" is appropriate for integers but would discard fractional parts if used for floating-point data. For decimals, choose a suitable floating-point format such as "%.8f". The delimiter must match between saving and loading. A one-dimensional array loads as a one-dimensional result, while a multi-row file loads as a two-dimensional result. Text files are readable and portable, but they are larger and slower to parse than NumPy’s binary formats for large numeric arrays.