Write matrix to file in python

Suppose I am getting a numpy matrix from some calculation. Here is my numpy matrix 'result1'::

    result1=
    [[   1.         0.         0.         0.00375   -0.01072   -0.      -1000.     ]
     [   2.         3.         4.         0.        -0.004    750.         0.     ]
     [   3.         3.         0.         0.         0.      -750.      1000.     ]]

Now I want to write this matrix in a text file named 'result.txt'. For this, I wrote the following code::

np.savetxt['result.txt', result1, fmt='%.2e']

But it is giving me all the elements of the matrix in one row.

    1.00e+00 0.00e+00 0.00e+00 3.75e-03 -1.07e-02 -1.14e-13 -1.00e+032.00e+00 3.00e+00 4.00e+00 0.00e+00 -4.00e-03 7.50e+02 0.00e+003.00e+00 3.00e+00 0.00e+00 0.00e+00 0.00e+00 -7.50e+02 1.00e+03

I want to write the matrix in the text file in the proper matrix format. How can I do this? I used keyword newline='\n' or newline='',but the result is same.

Thanks in advance...

=======

This edited part is for @Warren

try this one:

>>> import numpy as np
>>> mat=np.matrix[[[1, 2, 3],[4, 5, 6],[7, 8, 9]]]
>>> mat
matrix[[[1, 2, 3],
        [4, 5, 6],
        [7, 8, 9]]]
>>> np.savetxt['text.txt',mat,fmt='%.2f']

in my text.txt file, I am getting:

1.00 2.00 3.004.00 5.00 6.007.00 8.00 9.00

method

matrix.tofile[fid, sep='', format='%s']#

Write array to a file as text or binary [default].

Data is always written in ‘C’ order, independent of the order of a. The data produced by this method can be recovered using the function fromfile[].

Parametersfidfile or str or Path

An open file object, or a string containing a filename.

Changed in version 1.17.0: pathlib.Path objects are now accepted.

sepstr

Separator between array items for text output. If “” [empty], a binary file is written, equivalent to file.write[a.tobytes[]].

formatstr

Format string for text file output. Each entry in the array is formatted to text by first converting it to the closest Python type, and then using “format” % item.

Notes

This is a convenience function for quick storage of array data. Information on endianness and precision is lost, so this method is not a good choice for files intended to archive data or transport data between machines with different endianness. Some of these problems can be overcome by outputting the data as text files, at the expense of speed and file size.

When fid is a file object, array contents are directly written to the file, bypassing the file object’s write method. As a result, tofile cannot be used with files objects supporting compression [e.g., GzipFile] or file-like objects that do not support fileno[] [e.g., BytesIO].

  1. HowTo
  2. Python How-To's
  3. Write an Array to a Text File in Python

Created: December-20, 2021 | Updated: April-14, 2022

  1. Write an Array to Text File Using open[] and close[] Functions in Python
  2. Write an Array to Text File Using Content Manager in Python

Reading and writing files is an important aspect of building programs used by many users. Python offers a range of methods that can be used for resource handling. These methods may be slightly different depending on the format of the file and the operation being performed.

Besides the traditional way of creating files by clicking buttons, we can also create files using built-in functions such as the open[] function. Please note that the open[] function will only create a file if it does not exist; otherwise, it’s intrinsically used to open files.

Write an Array to Text File Using open[] and close[] Functions in Python

Since the open[] function is not used in seclusion, combining it with other functions, we can perform even more file operations such as writing and modifying or overwriting files.These functions include the write[] and close[] functions. Using these functions, we will create an array using NumPy and write it to a text file using the write function as shown in the program below.

import numpy as np

sample_list = [23, 22, 24, 25]
new_array = np.array[sample_list]

# Displaying the array

file = open["sample.txt", "w+"]

# Saving the array in a text file
content = str[new_array]
file.write[content]
file.close[]

# Displaying the contents of the text file
file = open["sample.txt", "r"]
content = file.read[]

print["Array contents in sample.txt: ", content]
file.close[]

Output:

Array contents in text_sample.txt:  [23 22 24 25]

We have created a text file named sample.txt using the open function in write mode in the example above. We have then proceeded to convert the array into string format before writing its contents to the text file using the write function. Using the open[] functions, we opened the contents of the text file in reading mode. The text file contents are displayed in the terminal and can also be viewed by physically opening the text file.

Similarly, we can also create a multi-dimensional array and save it to a text file, as shown below.

import numpy as np

sample_list = [[23, 22, 24, 25], [13, 14, 15, 19]]
new_array = np.array[sample_list]

# Displaying the array

file = open["sample.txt", "w+"]

# Saving the array in a text file
content = str[new_array]
file.write[content]
file.close[]

# Displaying the contents of the text file
file = open["sample.txt", "r"]
content = file.read[]

print["Array contents in sample.txt: ", content]
file.close[]

Output:

Array contents in sample.txt:  [[23 22 24 25]
[13 14 15 19]]

Write an Array to Text File Using Content Manager in Python

Alternatively, we can use the context manager to write an array to a text file. Unlike the open[] function, where we have to close the files once we have opened them using the close[] function, the content manager allows us to open and close files precisely when we need them. In Python, using the context manager is considered a better practice when managing resources instead of using the open[] and close[] functions. The context manager can be implemented using the with keyword shown below.

import numpy as np

new_list = [23, 25, 27, 29, 30]
new_array = np.array[new_list]
print[new_array]

with open["sample.txt", "w+"] as f:
  data = f.read[]
  f.write[str[new_array]]

Output:

[23 25 27 29 30]

In the example above, the context manager opens the text file sample.txt, and since the file does not exist, the context manager creates it. Within the scope of the context manager, we have written the array to the text file upon converting it into a string. Once we opt out of the indentation, the context manager closes the file automatically. Similarly, as shown below, we can also write multi-dimensional arrays to a text file using the context manager.

import numpy as np

new_list = [[23, 25, 27, 29],[30, 31, 32, 34]]
new_array = np.array[new_list]
print[new_array]

with open["sample.txt", "w+"] as f:
  data = f.read[]
  f.write[str[new_array]]

Output:

[[23 25 27 29]
[30 31 32 34]]

NumPy is a scientific library that offers a range of functions for working with arrays. We can save an array to a text file using the numpy.savetxt[] function. The function accepts several parameters, including the name of the file, the format, encoding format, delimiters separating the columns, the header, the footer, and comments accompanying the file.

In addition to this the NumPy function also offers the numpy.loadtxt[] function to load a text file.

We can save an array to a text file and load it using these two functions, as shown in the code below.

import numpy as np

new_list = [23, 24, 25, 26, 28]
new_array = np.array[new_list]
print[new_array]

np.savetxt["sample.txt", new_array, delimiter =", "]

content = np.loadtxt["sample.txt"]
print[content]

Output:

[23 24 25 26 28]

As shown below, we can also use these functions to save multi-dimensional arrays to a text file.

import numpy as np

new_list = [[23, 24, 25, 26, 28],[34, 45, 46, 49, 48]]
new_array = np.array[new_list]
print[new_array]

np.savetxt["sample7.txt", new_array, delimiter =", "]

content = np.loadtxt["sample7.txt"]
print[content]

Output:

[[23 24 25 26 28]
 [34 45 46 49 48]]

Related Article - Python Array

  • Initiate 2-D Array in Python
  • Count the Occurrences of an Item in a One-Dimensional Array in Python
  • Sort 2D Array in Python
  • Create a BitArray in Python
  • How do I save an array to a text file in Python?

    Use numpy..
    print[an_array].
    a_file = open["test.txt", "w"].
    for row in an_array:.
    np. savetxt[a_file, row].
    a_file. close[] close `a_file`.

    How do you make a matrix in Python?

    # Python program to convert a matrix to an array..
    # importing the required module..
    import numpy as np..
    # Creating a matrix using numpy..
    matrix = np.matrix["[4, 6, 7; 5, 2, 6; 6, 3, 6]"].
    # Using ravel[] function to covert matrix to array..
    array = matrix.ravel[].
    print[array].

    How do I save a large matrix in Python?

    try to use numpy. savetxt[] and numpy. loadtxt[] to write matrix to file and read file to a matrix.

    Chủ Đề