NumPy: Appending to file using savetxt()

Learn, how to append some data to an existing file using numpy savetxt() function in Python?
Submitted by Pranit Sharma, on February 25, 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.

Appending to file using savetxt()

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

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 code 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",,"\n")

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

# closing file

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


Example: NumPy: Appending to file using savetxt()

Python NumPy Programs »


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.