我想从现有的文本文件中提取键和值。在单独的变量中键入单独的变量和值。
文本文件(sample.txt)包含以下内容,
one:two
three:four
five:six
seven:eight
nine:ten
sample:demo
我能够从文本文件中读取内容,但我无法进一步提取键和值。
with open ("sampletxt.txt", "r") as hfile:
sp = hfile.read()
print (sp)
x=0
for line in sp:
sp.split(":")[x].strip()
x+=1
以上仅提取值,并在最后提供索引超出范围异常。
If we iterate through the file, i am expecting the output as below,
Key 0 = one
Key 1 = three
Key 2 = five
Key 3 = seven
key 4 = sample
Value 0 = two
Value 1 = four
Value 2 = six
Value 3 = eight
Value 4 = ten
这应该有效:
with open ("sampletxt.txt", "r") as hfile:
sp = hfile.read()
print (sp)
lines = sp.split("\n")
for line in lines:
# print("line:[{0}]".format(line))
parts = line.split(":")
print("key:[{0}], value:[{1}]".format(parts[0], parts[1]))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句