Python 如何读一整行,然后只读最后五个字符?
我是Python新手。我想从监控中读取JSON文件。文件看起来像这样 我只需要时间戳、系统名称(如“test-1”)以及电源、磁盘和CPU的数字 我的脚本是这样的Python 如何读一整行,然后只读最后五个字符?,python,file,Python,File,我是Python新手。我想从监控中读取JSON文件。文件看起来像这样 我只需要时间戳、系统名称(如“test-1”)以及电源、磁盘和CPU的数字 我的脚本是这样的 #!/usr/bin/env python3.3 import os import json with open('test.json', 'r') as f: distros_dict = json.load(f) for distro in distros_dict: pri
#!/usr/bin/env python3.3
import os
import json
with open('test.json', 'r') as f:
distros_dict = json.load(f)
for distro in distros_dict:
print(distro['"power [W]"'])
更新:
如何将它们写入变量
新样本数据:
[
{
"Area":"CLOUD",
"timestamp":"2019-11-06T00:00:00",
"Systeme":{
"test-4":{
"power [W]":181.05,
"disk [%]":52.28
},
"test-1":{
"power [W]":280.56,
"disk[%]":6.33,
"cpu[%]":0.1
},
"test-2":{
"power [W]":271.84,
"disk[%]":6.52,
"cpu[%]":0.1
},
"test-8":{
"power [W]":453.56,
"disk[%]":93.63,
"cpu[%]":5.04
}
}
}
]
我想要的输出变量是cpu、电源和磁盘
我不想将它们打印到命令行,而是想将它们写入json文件的三个变量中,其中multi-dict应该遵循以下格式:
[
{
"Area": "CLOUD",
"timestamp": "2019-11-06T12:24:25",
"Systeme": {
"test-1": {
"power [W]": 181.05,
"disk [%]": 52.28
},
"test-2": {
"power [W]": 199.67,
"disk [%]": 54.47
},
"test-3": {
"power [W]": 175.68,
"disk [%]": 10.17,
"cpu [%]": 22.43
}
}
},
{
"Area": "CLOUD",
"timestamp": "2019-11-06T12:24:25",
"Systeme": {
"test-1": {
"power [W]": 181.05,
"disk [%]": 52.28
},
"test-2": {
"power [W]": 199.67,
"disk [%]": 54.47
},
"test-3": {
"power [W]": 175.68,
"disk [%]": 10.17,
"cpu [%]": 22.43
}
}
}
]
您只需将每个字典中的值组合成一个字符串即可得到结果:
with open('test.json', 'r') as f:
distros_dict = json.load(f)
test_keys = ['power [W]', 'disk [%]', 'cpu [%]']
for distro in distros_dict:
for key, value in distro['Systeme'].items():
output_list =[]
output_list.append(key)
for single_system_key, single_system_value in distro['Systeme'][key].items():
if single_system_key in test_keys:
output_list.append(single_system_value)
print(' - '.join(str(e) for e in output_list))
最终输出为您提供:
test-1 - 181.05 - 52.28
test-2 - 199.67 - 54.47
test-3 - 175.68 - 10.17 - 22.43
test-1 - 181.05 - 52.28
test-2 - 199.67 - 54.47
test-3 - 175.68 - 10.17 - 22.43
设置你的字典(json格式,检查它是否使用正确的格式)
将字典作为json加载
import json
x = json.loads(json.dumps(dict))
在dict[Systeme]中循环并获取需要打印的所有属性。
我选择使用dict.get(“systeme”)
而不是dict[“systeme”]
,因为您在test-3中缺少cpu
for line in x["Systeme"]:
power = x.get("Systeme").get(line).get("power [W]", "")
disk = x.get("Systeme").get(line).get("disk [%]", "")
cpu = x.get("Systeme").get(line).get("cpu [%]", "")
print(f"{line} {power} {disk} {cpu}")
power, disk, cpu = "", "", ""
注意:上面的示例是Python3.7+,对于早期版本的Python,需要更改print语句:print(“%s%s%s%s”%(行、电源、磁盘、cpu))
您可以使用元组列表来存储变量。下面是一个如何做到这一点的示例
import json
import sys
data = None
with open('test.json', 'r') as file:
data = json.load(file)
# since we are dealing with input from another source, we should validate it every step of the way
# check if there was no data in the file
if not data:
sys.exit(0)
variables = [] # this list would contain tuples. The tuple would contain system name, cpu, power, and disk. Any missing data would be set as None
for distro in data:
if 'Systeme' not in distro: # we verify this attribute exists
continue
for system_name, system in distro['Systeme'].items():
variables.append(
(system_name, system.get('cpu[%]'), system.get('power [W]'), system.get('disk[%]'))
)
# now that we have them stored inside the 'variables' list, we can print them to verify that they are stored.
for system_name, cpu, power, disk in variables:
print(system_name, cpu, power, disk)
# do other stuff with these variables here if you want.
您可以尝试这种方法。您需要为此安装pandas pip安装程序
import json
import pandas as pd
data = json.load(open('data.json')) // asuming your data is in data.json
new_json=[]
for rec in data:
new_doc = {}
for key in rec:
if type(rec[key]) is str:
new_doc[key] = rec[key]
else:
for key1 in rec[key]:
if type(rec[key][key1]) is str:
new_doc[key+'_'+key1] = rec[key][key1]
else:
for key2 in rec[key][key1]:
if type(rec[key][key1][key2]) in [str,float,int]:
new_doc[key+'_'+key1+'_'+key2] = rec[key][key1][key2]
else:
print("don't support more nested json")
new_json.append(new_doc)
data = pd.DataFrame(new_json)
data.head() //peak into your new data structure][1]][1]
现在,您将拥有一个格式良好的表结构,可以对其执行任何查询。
因此,要获得所有类型1-power和时间戳,只需执行以下操作
data[['Systeme_test-1_power [W]','timestamp']]
我们可以从这里很容易地进行许多其他类型的查询和图形绘制。
如果您对谁是jason有疑问,请阅读panda docs以获取更多信息或发表评论???Stromverbrauch是power的德语单词,请解释为什么json末尾有
,…
,因为这不是正确的json格式。如果你想要多个dict-it-json,它应该是下面的格式[{},{}]
,3点在那里,因为我不想显示所有的500行代码document@leoStahlLinh的观点是文件应该以[
开头,而您没有在示例输入中显示它。它是否有[
一开始?我试过你说的,但现在我得到了这个错误test.py“,第10行,在发行版['Systeme']中的key,value():TypeError:string index必须是整数
因为你的json格式是错误的,请看我回答中json的格式如果其中一个键不存在,这将失败,例如test-3中的cpu那么你只需要检查键是否存在,这很简单,@leo Stahl我已经编辑了我的答案来检查键是否存在。现在如何将其写入d不同的变量您使用的是哪一个python版本?这是python 3.7+为早期版本的python添加了一个可选的打印函数My bad,这是python 3.6+它在python 3.7上不工作我得到错误回溯(最后一次调用):文件“/home/test/Dokument/Feab/test2.py”,第23行,在x[“Systeme”]:TypeError:字符串索引必须是整数
data[['Systeme_test-1_power [W]','timestamp']]