Python - How To Write an Array to a Text File in Python

ID : 464

viewed : 133

Tags : PythonPython Array

vote vote

91

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 HOW TO?