Reputation: 47
I am using the following code to read from a file:
G={}
for line in fin: # load data, create adj lists
lst=[]
size= len(line)
i=0
while (i<size):
if line[i] in ' \t\r\n': pass
else:
lst.append(int(line[i:i+2].strip()))
i=i+1
i=i+1
G[lst[0] ]=lst[1:]
print(G)
But G always turns out to be empty."foo1,txt" contains the following data:
1 15
2 6 10
3 10
4 9
5
Upvotes: 0
Views: 931
Reputation: 505
I have writen alternte code for appending data to list from file, you can refer if you want this code:
f = open('filename')
dic = []
for l in f:
v = l.split(' ')
v= map(lambda s: s.strip(), v)
dic=dic+v
print dic
output:
['1', '15', '2', '6', '10', '3', '10', '4', '9', '5', '']
Upvotes: 1
Reputation: 59
Try this, its most pythonic i think:
fin = open("foo1.txt")
G={}
for line in fin: # load data, create adj lists
lst = line.split()
lst = [int(x) for x in lst]
G[lst[0] ]=lst[1:]
print(G)
Upvotes: 0