why is this skipping readlines in what it returns? i went through debugger and found it thinks the second line of the txt file is the first and continues to skip every second line.
and it returns. i put the print of my_list in there to illustrate how it skips lines.
and etc. depending on how many more cities i add to the txt file. any suggestions on how to solve this problem?
my text file is 'cities.txt'
Code:
def get_distances(filename):
opener = open(filename)
d = {}
while file.readline(opener) != '':
'''converts a file with cities and distances into a dictionary with values
of distances from one city to other cities and then stores that dictionary
in a list with values specific to each city
'''
#storing the line which has been read in a list
read = file.readline(opener)
my_list = read.split(":")
my_list[1] = my_list[1].split()
max = len(my_list[1]) - 1
my_list.append(my_list[1][max])
my_list[1].pop()
if max > 1:
my_list[1] = my_list[1][0] + ' ' + my_list[1][1]
else:
my_list[1] = my_list[1][0]
print my_list
if d.has_key(my_list[0]):
d[my_list[0]].append((my_list[1],my_list[2]))
else:
d[my_list[0]] = [(my_list[1],my_list[2])]
return d
print get_distances('cities.txt')
Code:
['New York', 'Washington', '2']
['San Francisco', 'Mexico City', '3']
['Toronto', 'San Francisco', '6']
{'Toronto': [('San Francisco', '6')], 'San Francisco': [('Mexico City', '3')], 'New York': [('Washington', '2')]}
my text file is 'cities.txt'
Code:
Toronto:New York 3 New York:Washington 2 Washington:San Francisco 5 San Francisco:Mexico City 3 Toronto:Mexico City 7 Toronto:San Francisco 6
Comment