I would like to improve the run time of my code. It's currently very slow because I open a text file in append mode and write values to the end of the file and then I close the file each time I loop. Could someone help me store all my data in a python data structure and then output the results in the same format (i.e. all of the results in a text file with each value seperated by a space)? I am new to python and don't really understand how to implement this. Here's my code:
######import required packages########
import numpy
import math
#######Set working directory##########
import os
os.chdir('/Users/DevEnv/')
######Remove files generated from previous simulations#####
try:
os.remove('excitations.txt')
except OSError:
pass
##############Set Model Parameters#####################
n=2 #number of iterations -Change for desired number of loops
tlength=1501 #Length of time interval - DO NOT CHANGE
wu=100 #DO NOT CHANGE
N=250 #wu*T/4Pi approximately - DO NOT CHANGE
Pi=math.radians(180)
t=numpy.linspace(0,10,tlength)
Dw=wu/float(N)
for k in range(0,n):
A=[]
wi=[]
for i in range (0,N):
wi.append(Dw/2+i*Dw) #Middle of distribution
for j in range (0,tlength):
Aj=[]
phi=numpy.random.rand(N,1)*2*Pi #Generate random phase angle on 0,2pi
for i in range (0,N):
w=wi[i]
Sv=(((1+4*0.6**2*(w/15)**2)/((1-(w/15)**2)**2+4*0.6**2*(w/15)**2))*(0.0000753*(w/1.5)**4/((1-(w/1.5)**2)**2+4*0.6**2*(w/1.5)**2)))
Aj.append(math.sqrt(Sv*Dw)*2*math.cos(wi[i]*t[j]+phi[i]))
A.append(sum(Aj))
outFile = open('excitations.txt','a') #open/create the output file
for item in A:
outFile.write('%s ' %item)
outFile.write('\n')
outFile.close() #close the output file