Chris Castillo wrote:
I'm having some trouble reading multiple data types from a single text file.

say I had a file with names and numbers:

bob
100
sue
250
jim
300

I have a few problems. I know how to convert the lines into an integer but I don't know how to iterate through all the lines and just get the integers and store them or iterate through the lines and just get the names and store them.

please help.
------------------------------------------------------------------------

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor
You could do it with a list comprehension

>>> names = []
>>> numbers = []
>>> [numbers.append(int(line.strip())) if line.strip().isdigit() else names.append(line.strip()) for line in open('test.txt','rb') if line.strip()]
[None, None, None, None, None, None]
>>> names, numbers
(['bob', 'sue', 'jim'], [100, 250, 300])

The list comprehension would unfold to

for line in open('test.txt', 'rb'):
   if line.strip():
       if line.strip().isdigit():
           numbers.append(line.strip())
       else:
           names.append(line.strip())

And from there you can do what you like with the lists.

--
Kind Regards,
Christian Witts


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to