Append to file using savetxt() in NumPy
In this tutorial, you will learn how to append data to a file using savetxt() in Python.
Introduction:
A NumPy function called savetxt() is used to save an array to a text file. This function is useful for storing numerical data in a readable manner so that it can be quickly loaded again into a NumPy array using functions like loadtxt().
Import the necessary libraries:
import numpy as np import os
Define the Append Function:
For the purpose of reading, adding, and saving the data, create a function named “append_to_file”.
def append_to_file(file_name, new_data):
Check for the existence of the file:
To check if the file exists, we have to perform the following step. If it does, read the existing data and stack the new data on top of it.
if os.path.exists(file_name): existing_data = np.loadtxt(file_name) new_data = np.vstack((existing_data, new_data))
Save the data to the file:
To save the combined data back to the file, we have to use the ‘savetxt()’ function
np.savetxt(file_name, new_data, fmt='%f')
Check out an example:
Create new data to append, specify the file name, and call the function to append the data
new_data = np.array([[7, 8, 9]]) file_name = 'data.txt' append_to_file(file_name, new_data)
Complete Code:
import numpy as np import os def append_to_file(file_name, new_data): if os.path.exists(file_name): existing_data = np.loadtxt(file_name) new_data = np.vstack((existing_data, new_data)) np.savetxt(file_name, new_data, fmt='%f') # Example new_data = np.array([[7, 8, 9]]) file_name = 'data.txt' append_to_file(file_name, new_data)
Output:
The code appends the new data [7, 8, 9] to the existing file ‘data.txt’. If the file exists, the code adds the new data as a new row at the end of the existing data. If the file does not exist, the code creates the file and saves the new data in it. Each row in the file represents a list of numbers, with the numbers separated by spaces.
Additionally, you may also refer to:
Leave a Reply