如何从文本文件中提取键和值

人气:424 发布:2022-10-16 标签: text-files python extract python-3.x key-value

问题描述

我要从现有文本文件中提取键和值。键入单独的变量并输入单独的变量的值。

文本文件(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("
")
for line in lines:
  # print("line:[{0}]".format(line))
  parts = line.split(":")
  print("key:[{0}], value:[{1}]".format(parts[0], parts[1]))

269