我和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")
读者是列表,项目是单独的字典。
打印调用非常有效。它按照我的意愿打印出业务线。所以我不会发出个人信息(真正的单词是英文,长度相似,如果重要的话......一个字没有空格),输出如下:
α
布拉沃
查理
然而,当我写()同样的事情(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指标 - 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
布拉沃
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指标 - 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
查理
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指标 - 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()的工作方式有所不同。现在我已经解释了这个问题:
非常感谢你。如果可能的话,我认为这是解决问题的最佳方法。
答案 0 :(得分:0)
https://docs.python.org/3/library/functions.html#print
所有非关键字参数都转换为类似str()的字符串并写入流
如错误消息所示,您需要先将对象转换为字符串(但这适合您的目的),然后才能将其写入流中。
链接到Python 2.7文档:https://docs.python.org/release/2.7/library/functions.html#print
答案 1 :(得分:0)
您可以使用此代码重试并向我们提供输出吗?
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
现在你应该在打印中看到与文件
相同的内容