Writing an array to a text file in Python
Reading and writing files is an important aspect of building programs that are used by many users. Python provides a range of methods that can be used for resource handling. These methods may differ slightly depending on the format of the file and the operation being performed.
In addition to the traditional way of creating a file by clicking a button, we can also open()
create a file using built-in functions such as the function. Note that open()
the function will only create the file if it does not exist; otherwise, it essentially opens the file.
Writing an array to a text file using the open()
and functions
in Pythonclose()
Since open()
the write function is not used alone, by combining it with other functions, we can perform more file operations such as writing and modifying or overwriting files. These functions include the write write()
and overwrite 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 following program.
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]
In the above example, we have created a text file named using the open function in write mode sample.txt
. We then proceeded to convert the array into a string format and then write
write its contents to the text file using the write function. Using open()
the write function, we open the contents of the text file in read 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 multidimensional 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]]
Writing an array to a text file using the Content Manager in Python
Alternatively, we can use a context manager to write the array to a text file. Unlike open()
the __context__ function, where we have to close()
close the file after opening it using the __context__ function, a content manager allows us to open and close the file exactly when we need to. In Python, using context managers is considered a better practice when managing resources rather than using __context__ open()
and __context__ functions. A context manager can be implemented close()
using the __context__ keyword as shown below .with
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 above example, 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 write the array to the text file while converting it to a string. The context manager automatically closes the file once we choose to exit the indentation. Similarly, we can also write a multidimensional array to a text file using a context manager as shown below.
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 provides a range of functions for working with arrays. We can numpy.savetxt()
save an array to a text file using the function. The function accepts several parameters including the file name, format, encoding format, delimiter to separate columns, header, footer, and comments to accompany the file.
In addition, NumPy also provides numpy.loadtxt()
functions to load text files.
We can save the array to a text file and load it using these two functions as shown in the following code.
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 multidimensional arrays into text files.
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]]
For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.
Related Articles
Enumerating a dictionary in Python
Publish Date:2025/05/05 Views:98 Category:Python
-
The function in Python enumerate() returns an object of enumeration type and adds a counter variable to iterate over a list or other type of collection. It makes looping over such objects easier. When we pass an enumeration object to list()
Changing dictionary values in Python
Publish Date:2025/05/05 Views:108 Category:Python
-
This tutorial will discuss various ways to change the value of a particular key in Python dictionary. We can do this by using the following methods. dict.update() method for cycle. Dictionary Unpacking dict.update() How to change dictionary
Finding the maximum value in a Python dictionary
Publish Date:2025/05/05 Views:60 Category:Python
-
This tutorial explains how to get a key with the maximum value in Python. Since the method has changed from the previous Python versions, it also lists some sample codes to clarify the concepts. Use operator.itemgetter() the method to get t
How to read input from stdin in Python
Publish Date:2025/05/05 Views:124 Category:Python
-
This tutorial discussed stdin the methods of reading input from in Python. You can read directly from the console or from a file name specified in the console. In Python, fileinput.input() use stdin fileinput We can use the read module in P
Maximum integer in Python
Publish Date:2025/05/05 Views:55 Category:Python
-
This tutorial will discuss the maximum integer value in different versions of Python and how we can get it. In Python 2, integers and long integers are different data types. The maximum value of an integer is 2 31 -1. If the value exceeds t
Get a list of time zones using Python
Publish Date:2025/05/05 Views:107 Category:Python
-
When developing real-world applications, software developers must ensure that the application can support users from both their own country and other parts of the world. Since most countries have different time zones and many people around
Convert NumPy array to list in Python
Publish Date:2025/05/05 Views:101 Category:Python
-
Lists and arrays are the two most basic and commonly used collection objects in Python. They are both mutable and are used to store a collection of elements under a common name and each element has a specific location that can be used to ac
Appending 2D Arrays in Python
Publish Date:2025/05/05 Views:64 Category:Python
-
In Python, we can have ND arrays. We can use NumPy module to process arrays in Python. This tutorial demonstrated the different methods you can use to append values to a two-dimensional array in Python. Use append() the function to ap
Sliding average of NumPy arrays in Python
Publish Date:2025/05/05 Views:190 Category:Python
-
The sliding average is often used to study time series data by calculating the average of data at a specific time interval. It is used to eliminate some short-term fluctuations and study data trends. When studying stock price trends, the si