Writing list of basic variables to text file

混江龙づ霸主 提交于 2019-12-11 05:13:18

问题


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!


回答1:


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]))



回答2:


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!



来源:https://stackoverflow.com/questions/46934333/writing-list-of-basic-variables-to-text-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!