Writing data in files using NumPy focuses on storing NumPy arrays into external text files so they can be reused or updated later. NumPy mainly provides the np.savetxt() function for writing array data into text-based files.
Replacing Existing Content in a File
Replacing existing content means writing new array data to the same file, where the old data is completely removed and replaced. This is the default behavior of np.savetxt() if the file already exists, it overwrites the file without warning.
Example 1: This code creates a text file and stores initial array values in it.
- np.array([1, 2, 3]) creates a NumPy array with initial values
- np.savetxt('data.txt', a, delimiter=',') creates data.txt and writes the array values into it
import numpy as np
a = np.array([1, 2, 3])
np.savetxt('data.txt', a, delimiter=',')
Output

Example 2: This code writes new data to the same file, replacing the previously stored values.
- np.array([4, 5, 6]) creates new array data
- np.savetxt('data.txt', a, delimiter=',') overwrites the existing content of data.txt
- The original values (1, 2, 3) are removed and replaced with the new values
a = np.array([4, 5, 6])
np.savetxt('data.txt', a, delimiter=',')
Output

Appending Data to an Existing File
NumPy does not provide a direct append mode for np.savetxt(). To append data, existing file must first be loaded, then combined with new data and finally written back to the same file. This approach ensures the original data is preserved while adding new values.
This example shows how to read existing data from a text file using NumPy so it can be modified or extended later.
import numpy as np
x = np.loadtxt('data.txt', delimiter=',')
Output

Now, new values are added to the existing data and the combined result is written back to the same file.
- np.array([7, 8, 9]) creates new values to append
- np.concatenate((x, y)) merges existing and new data
- np.savetxt('data.txt', z, delimiter=',') saves the updated data back to the file
y = np.array([7, 8, 9])
z = np.concatenate((x, y))
np.savetxt('data.txt', z, delimiter=',')
Output
