0

I'm generating an array of Temperature (T) and another array of Position (X) and I'm able to plot it using simple command plt.plot(X, T). However, I'm struggling to get this data output to a text file. Please, can someone help me in this regard? Thank you. The len(T) prints 12 and len(X) prints 12 as well. This is how I'm trying in Python: These are the commands after a while loop, so the data is already generated. I would like to write both T[i] and X[i]

with open('Temp.txt', 'w') as fh: # this is where I like to write my Temperature data
    for i in range (12): # trying to loop around all the points, up to 12
        fh.write(T[i]) # trying to write temperature to the file, and if it works, need to write the same for the position, X. 

1 Answers1

0

ok maybe you should try this: of course, I think you want both values in the same file like "T[i] : X[i]"

T=(1,2,3,4,5)
X=(6,7,8,9,10)
outfile = open('outfile.txt', 'w') #open a file in same directory as the code to write
for a,b in zip(T,X):    # iterate over the list items
   outfile.write(str(a) +" : "+str(b)+ '\n') # write to the file
outfile.close() 

if you want each in seprate files then you should do something like this:

outfile1 = open('outfile1.txt', 'w') 
for a in T:
   outfile1.write(str(a) '\n') 
outfile1.close()
outfile2 = open('outfile2.txt', 'w') 
for a in X:
   outfile2.write(str(a) '\n') 
outfile2.close() 
prhmma
  • 843
  • 10
  • 18
  • Super, it works like a charm now. The example you gave is for tuple, and the data I have is list. Just changed the brackets to square ones, and all works for me. I have never come across zip (), will read more about it. I am only few months old in Python, thanks for sharing the knowledge and solving the problem. – Venkata Ravindra M V Oct 24 '19 at 15:50