Skip to content

How to Write a Multidimensional Array to a Text File in Python

Learn how to save 2D and 3D arrays to text files in Python using built-in file handling or NumPy's savetxt() for structured, readable output with custom delimiters and formatting.

Saving multidimensional arrays to text files is essential for data export, logging, sharing results, and creating human-readable output from numerical computations. Python offers several approaches, from manual formatting with built-in file handling to using NumPy's specialized functions. This guide covers writing 2D and 3D arrays to text files with clear examples, formatted output, and best practices.

Writing a 2D Array to a Text File

Using Built-in Python File Handling

The simplest approach converts each row to a string and writes it line by line:

array_2d = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

with open('output_2d.txt', 'w') as file:
    for row in array_2d:
        line = '\t'.join(str(value) for value in row)
        file.write(line + '\n')

print("2D array written to output_2d.txt")

File content (output_2d.txt):

1	2	3
4	5	6
7	8	9

Using a One-Liner with List Comprehension

array_2d = [
    [10, 20, 30],
    [40, 50, 60],
    [70, 80, 90]
]

content = '\n'.join(['\t'.join(map(str, row)) for row in array_2d])

with open('output_2d.txt', 'w') as file:
    file.write(content)

File content:

10	20	30
40	50	60
70	80	90

Choosing a Delimiter

You can use any separator (tabs, commas, spaces, or pipes):

array_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

with open('output_csv.txt', 'w') as file:
    for row in array_2d:
        file.write(', '.join(map(str, row)) + '\n')

with open('output_space.txt', 'w') as file:
    for row in array_2d:
        file.write(' '.join(map(str, row)) + '\n')

Outputs:

output_csv.txtplaintext
1, 2, 3
4, 5, 6
7, 8, 9
output_space.txtplaintext
1 2 3
4 5 6
7 8 9

Writing a 3D Array to a Text File

For three-dimensional arrays, separate each 2D "slice" with a blank line to maintain visual structure:

array_3d = [
    [[1, 2, 3, 4],
     [5, 6, 7, 8],
     [9, 10, 11, 12]],

    [[13, 14, 15, 16],
     [17, 18, 19, 20],
     [21, 22, 23, 24]]
]

with open('output_3d.txt', 'w') as file:
    for i, matrix in enumerate(array_3d):
        file.write(f"--- Slice {i} ---\n")
        for row in matrix:
            file.write(' '.join(str(val) for val in row) + '\n')
        file.write('\n')  # Blank line between slices

print("3D array written to output_3d.txt")

Output file is output_3d.txt:

output_3d.txtplaintext
--- Slice 0 ---
1 2 3 4
5 6 7 8
9 10 11 12

--- Slice 1 ---
13 14 15 16
17 18 19 20
21 22 23 24

Using NumPy for Efficient File Writing

NumPy provides np.savetxt() which handles formatting, delimiters, and headers automatically. This is the recommended approach for numerical arrays.

np.savetxt() for 2D Arrays

import numpy as np

array_2d = np.array([
    [1.5, 2.7, 3.14],
    [4.0, 5.5, 6.28],
    [7.1, 8.9, 9.42]
])

np.savetxt('numpy_output.txt', array_2d)

np.savetxt(
    'numpy_formatted.txt',
    array_2d,
    fmt='%.2f',                 # 2 decimal places
    delimiter='\t',             # Tab-separated
    header='Col1\tCol2\tCol3',  # Column headers
    comments=''                 # Remove '#' before header
)

print("NumPy arrays written to files")

Output file numpy_formatted.txt:

numpy_formatted.txtplaintext
Col1	Col2	Col3
1.50	2.70	3.14
4.00	5.50	6.28
7.10	8.90	9.42

Handling 3D Arrays with NumPy

np.savetxt() only supports 2D arrays directly. For 3D arrays, reshape or write each slice separately:

import numpy as np

array_3d = np.arange(1, 25).reshape(2, 3, 4)
print("Shape:", array_3d.shape) # Shape: (2, 3, 4)

with open('numpy_3d.txt', 'w') as file:
    for i, matrix in enumerate(array_3d):
        file.write(f"# Slice {i}\n")
        np.savetxt(file, matrix, fmt='%d', delimiter='\t')
        file.write('\n')

print("3D array written to numpy_3d.txt")

Output file numpy_3d.txt:

numpy_3d.txtplaintext
1	2	3	4
5	6	7	8
9	10	11	12

13	14	15	16
17	18	19	20
21	22	23	24

Reading the File Back

To verify your file was written correctly, read it back:

Reading with Built-in Python

with open('output_2d.txt', 'r') as file:
    for line in file:
        values = line.strip().split('\t')
        print(values)

Output:

['1', '2', '3']
['4', '5', '6']
['7', '8', '9']

Reading with NumPy

import numpy as np

loaded = np.loadtxt('numpy_formatted.txt', delimiter='\t', skiprows=1)
print("Loaded array:")
print(loaded)

Output:

numpy_formatted.txtplaintext
Loaded array:
[[1.5  2.7  3.14]
 [4.   5.5  6.28]
 [7.1  8.9  9.42]]

Common Mistake: Writing Without Proper Newlines

A frequent error is forgetting to add newline characters, causing all data to appear on a single line:

array_2d = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

with open('bad_output.txt', 'w') as file:
    for row in array_2d:
        file.write(' '.join(map(str, row)))

File content (incorrect):

bad_output.txtplaintext
1 2 34 5 67 8 9

The correct approach

with open('good_output.txt', 'w') as file:
    for row in array_2d:
        file.write(' '.join(map(str, row)) + '\n')

File content (correct):

good_output.txtplaintext
1 2 3
4 5 6
7 8 9

Formatting Floating-Point Numbers

When writing arrays with decimal values, control the precision to avoid excessively long numbers:

import numpy as np

data = np.random.rand(3, 4) * 100

print("Raw values:")
print(data)

np.savetxt('formatted.txt', data, fmt='%8.2f', delimiter=',')

with open('formatted.txt', 'r') as f:
    print("\nFormatted file content:")
    print(f.read())

Output:

formatted.txtplaintext
Raw values:
[[80.13466499 46.97305483 30.97382118 45.29292759]
 [76.4602344  14.44568402 31.71846976 39.6571253 ]
 [86.25690081 59.60845072 91.09635355  0.34838143]]

Formatted file content:
   80.13,   46.97,   30.97,   45.29
   76.46,   14.45,   31.72,   39.66
   86.26,   59.61,   91.10,    0.35

Quick Reference

Method Best For Handles 3D Format Control
Manual file.write() Simple lists, custom formatting Yes (with loops) Full control
'\n'.join() one-liner Quick 2D export No Basic
np.savetxt() NumPy arrays, large data 2D only (loop for 3D) fmt parameter
np.save() / np.savez() Binary format (not text) Yes N/A (binary)

For most use cases, np.savetxt() is the best choice for numerical 2D arrays, while manual file handling gives you the flexibility needed for 3D arrays, mixed data types, or custom file structures.

Navigation