bluegreen7hi

October 27th, 2009, 05:14 AM

Hello,

I am trying to read a set of integers into a list from a data file. The data is as follows:

John 70

Mike 200

Jane 120

Sue 170

I would like to end up with a list of integers, distances = [70, 200, 120, 170].

This is what I have so far:

distances = []

text_file = open("test.txt", "r")

for line in text_file:

for char in line.split(' '):

distances.append(char)

print(distances)

The output of this is:

['John', '70\n', 'Mike', '200\n', 'Jane', '120\n', 'Sue', '170\n']

Now how can I remove the names and the line break indicators from this list, and also convert each number to an int?

Am I even close or am I going about this all wrong? I believe this is a fairly simple process, but my numerous Google searches have returned nothing of use to me. Any help would be greatly appreciated.

Thanks!

I am trying to read a set of integers into a list from a data file. The data is as follows:

John 70

Mike 200

Jane 120

Sue 170

I would like to end up with a list of integers, distances = [70, 200, 120, 170].

This is what I have so far:

distances = []

text_file = open("test.txt", "r")

for line in text_file:

for char in line.split(' '):

distances.append(char)

print(distances)

The output of this is:

['John', '70\n', 'Mike', '200\n', 'Jane', '120\n', 'Sue', '170\n']

Now how can I remove the names and the line break indicators from this list, and also convert each number to an int?

Am I even close or am I going about this all wrong? I believe this is a fairly simple process, but my numerous Google searches have returned nothing of use to me. Any help would be greatly appreciated.

Thanks!