NumPy: Appending to file using savetxt()

Learn, how to append some data to an existing file using numpy savetxt() function in Python?
By Pranit Sharma Last updated : December 23, 2023

NumPy is an abbreviated form of Numerical Python. It is used for different types of scientific operations in python. Numpy is a vast library in python which is used for almost every kind of scientific or mathematical operation. It is itself an array which is a collection of various methods and functions for processing the arrays.

Problem statement

Suppose that we are given a data set and an existing file. We need to load this file and append the data set into this file using numpy.savetxt().

Appending to file using savetxt()

For this purpose, we first need to open the existing file in read-and-write mode and then we will create our data set. Once the file is opened and the data set is created, we can simply save the data set in the existing file using numpy.savetxt().

Let us understand with the help of an example,

Python program to append to file using savetxt()

# Import numpy
import numpy as np

# Creating a numpy array
arr = np.array([1,2,3,4])

# Opening a file
f = open('arr.csv','r+')

# Display file content
print("File content:\n",f.read(),"\n")

#appending data
for i in range(4):
     np.savetxt(f, arr)

# closing file
f.close()

# Display file content again
f = open('arr.csv','r')
print("File content:\n",f.read(),"\n")

Output

The output of the above program is:

Example: NumPy: Appending to file using savetxt()

Python NumPy Programs »

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.