I want to write a text file that has some lines in the following format:
result: variable1 +/- error1
result: variable2 +/- error2
And so on... So far I have:
f = open('file_{a}.txt'.format(a=some_name), 'w')
for i in range(len(variable)):
f.write('result: ', variable[i], '+/-', error[i], '\n')
Variable and error are floats, and some_name is a string.
But I'm getting an error:
TypeError: expected a string or other character buffer object
I guess I need to format the f.write
line differently but I can't figure out how. The file only needs to be read by humans, so that actual format can change.
Thanks!
From the
documentation
:So you can't pass in any number of
strings
separated bycommas
asarguments
. This is different to the wayprint()
works which excepts any number of arguments andformats
them for you...So that is why you are getting the
error
:How to fix it:
Fixing it is really easy, if you are sure
variable[i]
anderror[i]
arestrings
, you can either:format
them with.format
:or concatenate them with the
+
operand:Hope this helps!
If the problem is not the type of
variable[i]
orerror[i]
,try this: