打印工作正常,但是当我 write() 相同的东西到文件时,我得到 "Expected a character buffer object"?

Print works fine, but when I write() the same thing to file, I get "Expected a character buffer object"?

我正在使用 Splunk,但这似乎是我遇到的 python 相关问题。

通过 API 调用,我收到了一个词典列表,我正在遍历各个词典以打印出特定字段。它看起来像这样:

with open(lobFileName, "w+") as LOBs: #read/write, truncates file!
        for item in reader:
            for key in item: # iterate through the dictionary
                if key == 'cost_center':
                    print item[key] # TODO: Replace this with however I display it on the webpage.
                    LOBs.write(item[key]) # write the LOBs to the file, one LOB per line
                    LOBs.write("\n")

reader是列表,item是个别字典。

打印调用工作 完美。 它打印出我想要的业务线,这是应该的。所以我不给出个人信息(真正的单词是英语,长度相似,如果重要的话......一个单词没有空格),输出如下:

Alpha

Bravo

Charlie

但是,当我写 () 相同的东西 (item[key]) 时,我得到一个:"expected a character buffer object" 错误。

所以,我将其更改为LOBs.write(str(item[key])。但是当我写文件时,我得到的不是上面的输出,而是 (A,B,C 加粗以便于查看):

Alpha~1116~7F4F9983-72F8-48C8-BFAD-82C0F713CA34 1116:18886924 1437770160 1 07-24-2015 16:35:59.888 -0400 INFO Metrics - group=per_index_thruput, series="clo", kbps=3.596555, eps=13.129038, kb=111.493164, ev=407, avg_age=2.422604, max_age=27 199 ['ksplidx4c', '_internal'] splunkd .888 2015-07-24T16:35:59.888-04:00

Bravo

psplfwd1a _internal 1 clo /opt/splunk/var/log/splunk/metrics.log splunkd ksplidx4c _internal~1116~7F4F9983-72F8-48C8-BFAD-82C0F713CA34 1116:18886931 1437770160 1 07-24-2015 16:35:59.888 -0400 INFO Metrics - group=per_index_thruput, series="cos", kbps=564.982992, eps=1387.129659, kb=17514.464844, ev=43001, avg_age=2.232622, max_age=11 198 ['ksplidx4c', '_internal'] splunkd .888 2015-07-24T16:35:59.888-04:00

Charlie

psplfwd1a _internal 1 cos /opt/splunk/var/log/splunk/metrics.log splunkd ksplidx4c _internal~1116~7F4F9983-72F8-48C8-BFAD-82C0F713CA34 1116:18886952 1437770160 1 07-24-2015 16:35:59.888 -0400 INFO Metrics - group=per_index_thruput, series="issofim", kbps=1.250410, eps=12.193554, kb=38.762695, ev=378, avg_age=1.738095, max_age=8 195 ['ksplidx4c', '_internal'] splunkd .888 2015-07-24T16:35:59.888-04:00

现在,我知道这看起来很大,但你不知道那是什么意思 听我说完:)。显然 write() 的工作方式与 print() 的工作方式有所不同。解释完了,我的问题是:

非常感谢。如果可能的话,我认为这^是解决问题的最佳方法。

https://docs.python.org/3/library/functions.html#print

All non-keyword arguments are converted to strings like str() does and written to the stream,

如错误消息所示,您需要先将对象转换为字符串(但适合您的目的),然后才能将其写入流。


Link 到 Python 2.7 文档:https://docs.python.org/release/2.7/library/functions.html#print

您能否改用此代码重试并向我们提供输出结果?

with open(lobFileName, "w+") as LOBs: #read/write, truncates file!
        for item in reader:
            for key in item: # iterate through the dictionary
                if key == 'cost_center':
                    print "%s\n" % (item[key]) # TODO: Replace this with however I display it on the webpage.
                    LOBs.write("%s\n" % (item[key])) # write the LOBs to the file, one LOB per line

现在您应该会在打印件中看到与文件中相同的内容