How To Write A Multidimensional Array To A Text File?
Last Updated :
24 Jan, 2024
In this article, we will explain how to write a multidimensional array to a text file with the help of a few examples. Writing a multidimensional array to a text file is a straightforward process, and it allows you to print the array directly to the text file in a simple manner.
Write A Multidimensional Array To A Text File
To write a multidimensional array to a text file in Python, follow the steps below
Create a Virtual Environment
Create the virtual environment using the below command.
python -m venv env
.\env\Scripts\activate.ps1
Create an Output File
Create a Text file in the same folder for printing the Multidimensional Array.
File Structure

Code Example
Example 1: Write Two Dimensional Array To A Text File
In this example, below code creates a 2D array named two_d_array
, converts it to a formatted string (array_string
) with rows separated by newline and elements within each row separated by a tab, then writes the string to a file named 'output.txt'. Finally, it prints the original 2D array and a message indicating that the output has been written to 'output.txt'.
Python3
# Example 2D Array
two_d_array = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Convert 2D Array to String
array_string = '\n'.join(['\t'.join(map(str, row)) for row in two_d_array])
# Write to File
with open('output.txt', 'w') as file:
file.write(array_string)
# Display Output
print("2D Array:")
for row in two_d_array:
print(row)
print("\nOutput Written to output.txt")
Output :
1, 2, 3
4, 5, 6
7, 8, 9
Example 2: Write Three Dimensional Array To A Text File
In this example, below Python code defines a three-dimensional array with dimensions 2x3x4, initializes it with sequential values, and then writes the array to an "output.txt" file. The array is created using nested list comprehensions, filled with values incrementally, and each element is written to the file with space separation. Two additional lines of code are suggested to add a newline after each row and a blank line after each second dimension in the file.
Python3
# Define the dimensions of the array
first_dimension = 2
second_dimension = 3
third_dimension = 4
# Initialize the three-dimensional array with zeros
three_dimensional_array = [[[0 for _ in range(third_dimension)]
for _ in range(second_dimension)]
for _ in range(first_dimension)]
# Fill the array with values
value = 1
for i in range(first_dimension):
for j in range(second_dimension):
for k in range(third_dimension):
three_dimensional_array[i][j][k] = value
value += 1
# Open a file for writing
with open("output.txt", "w") as file:
# Write the three-dimensional array to the file
for i in range(first_dimension):
for j in range(second_dimension):
for k in range(third_dimension):
file.write(f"{three_dimensional_array[i][j][k]} ")
file.write("\n")
file.write("\n")
# Print a message
print("\nOutput Written to output.txt")
Output :
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
17 18 19 20
21 22 23 24
Conclusion
In Python, the process of writing a multidimensional array to a text file involves initially converting the array into a string representation and subsequently saving it using file handling functions. This tutorial covers fundamental concepts of arrays, file management, and the necessary steps to accomplish this task. We demonstrated this process with a basic 2D list, converting it into a string and writing the result to a file to exemplify handling a 2D array
Similar Reads
Write Multiple Variables to a File using Python Storing multiple variables in a file is a common task in programming, especially when dealing with data persistence or configuration settings. In this article, we will explore three different approaches to efficiently writing multiple variables in a file using Python. Below are the possible approach
2 min read
How to save a NumPy array to a text file? When working with data it's important to know how to save NumPy arrays to text files for storage, sharing and further analysis. There are different ways from manual file handling to using specialized NumPy functions. In this article, we will see how to save a NumPy array to a text fileMethod 1: Usin
3 min read
How to Write an ArrayList of Strings into a Text File? In Java, ArrayList is a class in the java.util package. It facilitates the creation of dynamic arrays that can dynamically grow or shrink as elements are added or removed. This class is part of the Java Collections Framework. An ArrayList of strings is converted into a text file and implemented usin
2 min read
How to Write a Struct to a Binary File in C? C file handling allows users to store the data from a C program to a file in either the text or the binary format. In this article, we will learn how to write a struct to a binary file in C. Writing Structure into a Binary File in CTo write a struct to a binary file, we can use the fwrite() function
2 min read
How to Get Value of Multidimensional Array in C? Prerequisite: Array in C An array is a type of data structure where we can store multiple elements of similar data types. A multidimensional array can be termed an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays are stored in row-major order. Declaration
8 min read
How to iterate a Multidimensional Array? Multidimensional arrays are arrays that have more than one dimension. For example, a simple array is a 1-D array, a matrix is a 2-D array, and a cube or cuboid is a 3-D array but how to visualize arrays with more than 3 dimensions, and how to iterate over elements of these arrays? It is simple, just
8 min read
How to Read and Write Arrays to/from Files in C++? In C++, an array is a collection of elements of the same type placed in contiguous memory locations. A file is a container in a computer system for storing information. In this article, we will learn how to read and write arrays to/from files in C++. Example: Input: Array = {1, 2, 3, 4, 5}Output: //
2 min read
Multidimensional Array in R Arrays are the R data objects which can store data in more than two dimensions. For example: If we create an array of dimensions (2, 3, 4) then it creates 4 rectangular matrices each with 2 rows and 3 columns. These types of arrays are called Multidimensional Arrays. Arrays can store only data types
3 min read
How to Initialize Array With Values Read from a Text File in C++? In C++, arrays store a fixed-size collection of elements of the same type. We can initialize these elements with any valid value. In this article, we will learn to initialize a C++ array with values read from a text file. Example: Input:Text File = âarray.txtâ // contains 1 2 3 4 5Output:// Read the
2 min read
How to write Into a File in PHP ? In this article, we are going to discuss how to write into a text file using the PHP built-in fwrite() function. The fwrite() function is used to write into the given file. It stops at the end of the file or when it reaches the specified length passed as a parameter, whichever comes first. The file
2 min read