1

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 :

enter image description here

Thanks a lot

1
  • Did you try using open() method? If not you can study from here: w3schools.com/python/ref_func_open.asp and then you can append or directly write into your file. Just open this link you will come to know. Commented May 8, 2020 at 8:47

2 Answers 2

1

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()    
Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

Thank you for your comment. I tried to run and It showed that : f.write("#",iyr1+1998," ",r2T2m_mn[iyr1],"\n") TypeError: write() takes exactly one argument (5 given)
I got the solution. Thank you for your time

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.