从python中的txt文件读取值

时间:2018-09-07 09:07:42

标签: python python-3.x

我想从txt文件中读取所有值并存储例如:     20,110,60,140     10,210,80,240     并存储值,例如

 id[0] = 20 , id[1] = 110 , id[2] = 60 , id[3] = 140 and
 id1[0] = 10 , id1[1] = 210 , id1[2] = 80 , id[3] = 240

如何更改下面的代码以获取上述格式的值

def main():
  # Txt read
  global id
  id=[]
  input = open('log.txt', 'r')
  for eachLine in input:
    substrs = eachLine.split(',', eachLine.count(','))
    for strVar in substrs:
      if strVar.isdigit():
        id.append(int(strVar))

main()
print(id[3])`

1 个答案:

答案 0 :(得分:1)

创建动态变量不是一个好主意,因此您可以尝试如下操作:

f = open("log.txt", "r")
ids = []
for i in f.readlines():
    sub_id = list(map(int,i.split(",")))
    ids.append(sub_id)
print(ids)
# [[20, 110, 60, 140],[10, 210, 80, 24]]

或:

f = open("log.txt", "r")
ids = {}
for j,i in enumerate(f.readlines()):
    sub_id = list(map(int,i.split(",")))
    ids['id'+str(j)] = sub_id
print(ids)
# {'id1': [10, 210, 80, 24], 'id0': [20, 110, 60, 140]}