Reputation: 15
I have to save my results to txt file but no idea for this. I greatly need some of you can help me. I really appreciate. My code :
import pandas as pd
import numpy as np
import glob
filenames = glob.glob('E:\koppen-master\dat_Viet\T2m_*.txt')
for g in filenames:
print("#",g)
data1=np.loadtxt(fname=g,comments="#")
nyr1=len(data1[:,1])/31
nyr1=int(nyr1)
r3T2m=np.reshape(data1[:,1:13],(nyr1,31,12))
r2T2m_mn=np.zeros(shape=(nyr1,12))
iyr1=0
while iyr1 < nyr1:
imn1=0
while imn1<12:
idy1=0
ndy1=0
while idy1 <31:
if r3T2m[iyr1][idy1][imn1]>=-10.:
ndy1=ndy1+1
r2T2m_mn[iyr1][imn1]=r2T2m_mn[iyr1][imn1]+r3T2m[iyr1][idy1][imn1]
idy1=idy1+1
r2T2m_mn[iyr1][imn1]=round(r2T2m_mn[iyr1][imn1]/float(ndy1),2)
imn1=imn1+1
print ("#",iyr1+1998," ",r2T2m_mn[iyr1])
iyr1=iyr1+1
My result like this :
Thanks a lot
Upvotes: 1
Views: 2105
Reputation: 887
Add this line of code above your for loop as shown below :
f = open("results.txt", "w")
for g in filenames:
Add this line of code after your print statement as shown below :
print ("#",iyr1+1998," ",r2T2m_mn[iyr1])
f.write("#" + (iyr1+1998) + " " + r2T2m_mn[iyr1] + "\n")
Add this line at the end of your code (outside all loops) :
f.close()
Upvotes: 0
Reputation: 3270
You can try to use the python file, see section 'Reading and Writing Files' for more information. Just above your for, include that line:
with open('output.txt', 'w') as f:
try:
#put your for and while loops here
Right after your print statement include this line (same indentation level):
f.write('#{} {}\n'.format(int(iyr1)+1998, r2T2m_mn[iyr1]))
At the end of the file just put (indentation level from try
statement):
except Exception as err:
print('There was an error. Detail: {}'.format(err))
finally:
f.close()
Upvotes: 1