exsonic01
exsonic01

Reputation: 637

numpy loadtext and savetxt multiple files?

I hope to read, calculate, and print out multiple files of same format.

filenames2 = ["AAA", "BBB", "CCC", "DDD", "EEE"]
for filename2 in filenames2:
   with loadtxt (filename2, float) as data:
      a1 = data[:,0]
      b1 = data[:,3]
      c1 = data[:,4]
      d1 = data[:,5]
      e1 = data[:,6]
     %% DO something with all those data. 
   z = numpy.array((calculated_a11, calculated_b11, calculated_c11), dtype = float)
   z2 = z.T
   numpy.savetxt('avegedoutput_%s.txt' %filenames2, z2.reshape((1000,3)), fmt='%i %f %f')

I hope to write in this way, so that hope to work with multiple files. But it seems that numpy savetxt and loadtxt are not working in this way.... Welcome any suggestion.

Thanks in advance.

ps) Also, should I need to make empty matrices for those data reading section? Seems like those commands make these errors: "TypeError: 'file' object is unsubscriptable".

I think that I need to make zero matrices, and put data into those matrices like I do in Matlab. Is this right?

Upvotes: 1

Views: 842

Answers (1)

elyase
elyase

Reputation: 40973

numpy.loadtxt takes a filename(string) and returns a numpy array. So you don't need the with clause:

filenames2 = ["AAA", "BBB", "CCC", "DDD", "EEE"]
for filename2 in filenames2:
    data = np.loadtxt(filename2)
    a1 = data[:,0]
    # ...
    np.savetxt('output_filename.txt', z, ...)

So far I don't see any need to make zero matrices in your code. data will get filed with the contents of the file and a1, b1, ..., will get their contents from data.

Upvotes: 2

Related Questions