Writing list of basic variables to text file

2019-08-10 23:06发布

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!

2条回答
可以哭但决不认输i
2楼-- · 2019-08-10 23:18

From the documentation:

f.write(string)

writes the contents of string to the file, returning the number of characters written.

So you can't pass in any number of strings separated by commas as arguments. This is different to the way print() works which excepts any number of arguments and formats them for you...

So that is why you are getting the error:

TypeError: expected a string or other character buffer object

How to fix it:

Fixing it is really easy, if you are sure variable[i] and error[i] are strings, you can either:

format them with .format:

f.write('result: {} +/- {}\n'.format(variable[i], error[i]))

or concatenate them with the + operand:

f.write('result: ' + variable[i] + ' +/- ' + error[i] + '\n')

Hope this helps!

查看更多
Emotional °昔
3楼-- · 2019-08-10 23:24

If the problem is not the type of variable[i] or error[i],try this:

f = open('file_{a}.txt'.format(a=some_name), 'w')
for i in range(len(variable)):
   f.write('result: {0} +/- {1}\n'.format(variable[i],error[i]))
查看更多
登录 后发表回答