user3328741
user3328741

Reputation: 11

Writing into text file

f = open("outputdata.txt", 'w')
    for i in range(len(mydose)):
        t = (mygrid[i]+mygrid[i+1])/2.0
        f.write("%12.6f %12g %12g" % (t, mydose[i], myerrs[i]*mydose[i]))

The previous code gives me outputdata.txt file with all data in a single line. Now, I want to write in 3 columns which are t, mydose[i] and *myerrs[i]mydose[i]. I tried:

f = open("outputdata.txt", 'w')
    for i in range(len(mydose)):
        t = (mygrid[i]+mygrid[i+1])/2.0
        f.write("%12.6f %12g %12g" % (t, mydose[i], myerrs[i]*mydose[i],'\n'))

which gave me Typeerror: not all arguments converted during string formatting.

Could somebody please help me fixing this problem?

Upvotes: 0

Views: 158

Answers (4)

emazzotta
emazzotta

Reputation: 2039

You forgot "%s":

f.write("%12.6f %12g %12g %s" % (t, mydose[i], myerrs[i]*mydose[i],'\n'))

Upvotes: 1

wim
wim

Reputation: 362468

This should fix your problem:

with open("outputdata.txt", 'w') as f:
    for (i, (err, dose)) in enumerate(zip(myerrs, mydose)):
        t = (mygrid[i] + mygrid[i + 1]) / 2.
        f.write("%12.6f %12g %12g\n" % (t, dose, err * dose))

In future you might consider using csv module (with space separator) to write this file.

Upvotes: 1

Ron
Ron

Reputation: 55

Ues the code as blow:

f = open("outputdata.txt", 'w')
for i in range(len(mydose)):
    t = (mygrid[i]+mygrid[i+1])/2.0
    f.write("%12.6f %12g %12g\n" % (t, mydose[i], myerrs[i]*mydose[i]))

Upvotes: 0

jonjohnson
jonjohnson

Reputation: 423

Just add the \n at the end

f.write("%12.6f %12g %12g\n" % (t, mydose[i], myerrs[i]*mydose[i]))

Upvotes: 2

Related Questions