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().

To append data to a file using savetxt() with NumPy involves these steps:

  • Reading Existing Data:  Utilize NumPy to read data from a text file if it already exists
  • Appending New Data:  Combine the existing data with new data
  • Saving the Combined Data:  Write the combined dataset back to the file.

By the end of this tutorial, you will effectively maintain and update data files using NumPy. You will ensure that you correctly insert new data without overwriting previous data. Now let’s get started!

 

Import the necessary libraries:

Begin by importing the NumPy library, which you will use for numerical operations, and the os module to verify the availability of the file.

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

Your email address will not be published. Required fields are marked *