-1

How to print string in data file ? I have checked this Python Print String To Text File. But this is not really helping me. The part of the code is like this :

for k in range(len(energy)):
        str = "%12.4e %12.4e " %(energy[k], spectra[0][k])
        for j in range(1,spectra.shape[0]):
            str += "%12.4 " % spectra[j][k]
        print str

Now i want this string output in a data file. How this can be done ? Any help is appreciated.

Community
  • 1
  • 1
Suvo
  • 1,318
  • 11
  • 13

1 Answers1

0

Don't name a variable str. That's the name of a builtin function.

To answer your question: Open a file and write to it.

with open("/tmp/out.txt", "w") as o:    
    for k in range(len(energy)):
        s = "%12.4e %12.4e " %(energy[k], spectra[0][k])
        for j in range(1,spectra.shape[0]):
            s += "%12.4 " % spectra[j][k]
        o.write(s)

Note that this does not add newlines! If you need them, add a \n at the end of s.