1

I would like to write certain text in a certain format to txt with this code:

textf = open("output.txt","w")

for i in range(len(x1)):
    textf.write("sf"+repr(i+2) +": -1x1_1+"+ repr((x2[i]))+"x2_1+"+repr(x3[i])+"x3_1")
    textf.write("\n")

    textf.close()

The output is this:

sf2: -1x1_1+array([ 100.])x2_1+array([ 100.])x3_1
sf3: -1x1_1+array([ 91.02295278])x2_1+array([ 90.9906232])x3_1
sf4: -1x1_1+array([ 101.25508941])x2_1+array([ 138.07783278])x3_1

But i would like to see only the values in the array:

sf2: -1x1_1+100x2_1+100x3_1
sf3: -1x1_1+91.02295278x2_1+90.9906232x3_1
sf4: -1x1_1+101.25508941x2_1+138.07783278x3_1

Thanks in advance!

1 Answer 1

1

repr() will give you a representation of the object. For simple objects, such as integers and floats, this will be the literal value, but this isn't the case for everything. What you want here is to use the value of the array in string interpolation. It's also recommended to handle files with the with syntax.

with open("output.txt","w") as textf:
    for i in range(len(x1)):
        textf.write('sf{0}: -1x1_1+{1:f}x_1+{2:f}x3_1\n'.format(i+2, x2[i], x3[i]))

By adding further numbers in the format, e.g. {:5.3f} you can control the maximum width the float will take up and how many digits after the decimal point will be shown. For example,

>>> '{:10.5f}'.format(3.25)
'   3.25000'

And for filling the spaces to the left with zeros:

>>> '{:010.5f}'.format(3.25)
'0003.25000'

Finally, if you have a lot of lines to write, calling write() repeatedly could be slow. It'd be more efficient to create a string of all the lines first and then write them in one go.

lines = ['sf{0}: -1x1_1+{1:f}x_1+{2:f}x3_1'.format(i+2, x2[i], x3[i]) for i in range(len(x1))]
with open("output.txt","w") as textf:
    textf.write('\n'.join(lines))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.