[英]How to convert text file into a dictionary in Python
我正在尝试获取一个文本文件并将其转换为 Python 中的字典。 文本文件具有键/值格式。 当我运行我的代码时,我得到了这个错误。
Traceback (most recent call last):
File "testCpu.py", line 4, in <module>
(key,val) = line.split()
ValueError: too many values to unpack (expected 2)
这是我的代码。
d = {}
with open("/proc/cpuinfo") as f:
for line in f:
(key,val) = line.split()
d[str(key)] = val
print(d)
这是文本文件的一部分。
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 69
model name : Intel(R) Core(TM) i3-4030U CPU @ 1.90GHz
stepping : 1
microcode : 0x25
cpu MHz : 1895.570
cache size : 3072 KB
physical id : 0
siblings : 4
core id : 0
cpu cores : 2
apicid : 0
有人可以帮我吗?
你很接近:
key, val = line.split(':') # split into "left" and "right", relative to ":"
key = key.rstrip(' ') # remove whitespaces from the left
val = val.lstrip(' ') # remove whitespaces from the right
# or, use .lstrip(' ') on each to remove whitespaces from both sides
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.