将基本变量列表写入文本文件

问题描述:

我想编写一个文本文件,其中包含以下格式的行:

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

变量和错误是浮点数,some_name是字符串.

Variable and error are floats, and some_name is a string.

但是我遇到一个错误:

TypeError:预期为字符串或其他字符缓冲区对象

TypeError: expected a string or other character buffer object

我想我需要以不同的方式设置f.write行的格式,但是我不知道该怎么做.该文件只需要人类阅读,因此实际格式可以更改.

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.

谢谢!

如果问题不是variable[i]error[i]的类型,请尝试以下操作:

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