Skip to main content

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

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:

# 2D array (list of lists)
array_2d = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]

# Write to file with tab-separated values
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]
]

# Convert entire array to a formatted string
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]]

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

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

Outputs:

1, 2, 3
4, 5, 6
7, 8, 9
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:

# 3D array: 2 matrices, each 3 rows × 4 columns
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:

--- 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]
])

# Save with default settings (space-separated, scientific notation)
np.savetxt('numpy_output.txt', array_2d)

# Save with custom formatting
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:

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)

# Method 1: Write each 2D slice separately
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:

# 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
tip

For large numerical arrays, np.savetxt() is significantly faster and more memory-efficient than manual Python loops. It also handles floating-point formatting, scientific notation, and custom delimiters automatically.

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:

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]]

# INCORRECT: everything on one line
with open('bad_output.txt', 'w') as file:
for row in array_2d:
file.write(' '.join(map(str, row)))

File content (incorrect):

1 2 34 5 67 8 9

The correct approach

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

File content (correct):

1 2 3
4 5 6
7 8 9
warning

Always append '\n' after each row when writing manually. Without it, all rows merge into a single line, making the file unreadable and impossible to parse back into an array.

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

# Without formatting: too many decimal places
print("Raw values:")
print(data)

# With formatting: clean output
np.savetxt('formatted.txt', data, fmt='%8.2f', delimiter=',')

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

Output:

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

MethodBest ForHandles 3DFormat Control
Manual file.write()Simple lists, custom formattingYes (with loops)Full control
'\n'.join() one-linerQuick 2D exportNoBasic
np.savetxt()NumPy arrays, large data2D only (loop for 3D)fmt parameter
np.save() / np.savez()Binary format (not text)YesN/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.