Asar
Asar

Reputation: 21

Reading values from txt file in python

I like to read all value from a txt file and store e.g : 20,110,60,140 10,210,80,240 and store the values e.g

 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

how can I change my code below to get values in a format discussed above

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])`

Upvotes: 0

Views: 1376

Answers (1)

Vikas Periyadath
Vikas Periyadath

Reputation: 3186

Creating dynamic variables is a bad idea, so you can try like this :

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]]

or :

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]}

Upvotes: 1

Related Questions