My code generates a 2 dimensional array, which I want to save into a file. This can be easily done using numpy.savetxt as shown in the sample code. But I wish to do something different. In the following code I generate random walks for 5 walkers. For each walk, I generate positions of the walker for some time and store the positions in a list. After each walk is completed , I add the whole list containing walker's positions, as a new row to an already existing array S_data. At the end of the next walk (or iteration), I add the list of position for the next walker and so on.. So by the end of each walker's iteration, a new row is added to S_data. At the end of all walks , this S_data is finally saved to an external file using numpy.savetxt .
import numpy as np
no_of_walkers = 5
t_max = 10
S_data=np.zeros(t_max)
for R in range(no_of_walkers):
position = []
x = 0.0
for t in range(t_max):
x = x + np.random.randint(-1, 2)
position.append(x)
S_data = np.vstack([S_data, position])
S_data = np.delete(S_data, obj=0, axis=0)
np.savetxt('data_file.txt', S_data)
What I wish to do is, at the end of each walk, instead of adding the position list to S_data, I want to write it to an external file. Again at the end of next iteration, I will add the position list for the next walker as a new line to the external file, and so on. I want to do this because, I will have to run this code for large number of walkers and also for longer times, so then my code will consume lot of RAM, which I want to avoid. Is there a pythonic way to export lists to the same external file at the end of each iteration, without overwriting the previous data?
savetxtan open file object, instead of the file name. Or you can use a file file directly.savetxtjust loops through the rows ofS_data, formating each and using a plain file write. If you can print the data line by line (with desired formatting) you can write to a file line by line.