0

I have a .txt file like this:

John 26
Mary 48
Nick 34

I want import them and put them in a list so that I can find specific elements. For example age[1] would have the value 48, name[1] the value Mary etc.

I tried doing

import sys,random
f = open('example.txt', 'r')
for line in f:
        tokens=line.split()
        a=tokens[0]
        print a[1]

but the result of print a[1] is the second letter of each string.

2 Answers 2

3

Instead of a[1], you want tokens[1].

This is the value of a, which is the first element of tokens:

Nick

But the second element of tokens is the age:

"34"

As @user mentioned, you probably wanted to have it as integer, not a string. You can convert it to integer:

a = int(tokens[1])

@thefourtheye proposed a nice solution. I think i'll propose to store it in a dictionary:

with open('example.txt') as f:
    ages = {}
    for line in f:
        d = line.split()
        ages[d[0]] = int(d[1])

And here is ages:

{'John':26, 'Mary':48, 'Nick':34} 

To retrieve the age of John:

print(ages['John'])

Hope this helps!

Sign up to request clarification or add additional context in comments.

6 Comments

Might as well preempt the next bug while we're at it: tokens[1] is a string, so trying to do math with it won't work properly unless you convert it to an int first.
We don't yet know that OP is going to try to do math on the age field. :-)
Yes but tokens[1] prints the whole column. How can I select the specific value 34? tokens[1][2] returns the 3rd character...
@qwrrty: Maybe he'll do math on the name field as a base-36 number? :)
@Galil: tokens[1] is not the whole column, it's the age of the current line. Presumably the reason you're seeing a whole column is that you're just trying to print all of the names and ages, rather than storing them in any age and name lists. To do that, just age.append(a) instead of print(a). (Or do it thefourtheye's way.)
|
2
  1. While reading from a file, always use with, so that you dont have to worry about closing the file.
  2. Then, you can read lines and split them and finally unzip them like this

    with open('Input.txt', 'r') as inFile:
        names, ages = zip(*(line.rstrip().split() for line in inFile))
        print names, ages
    

    Output

    ('John', 'Mary', 'Nick') ('26', '48', '34')
    
  3. You can access the individual names and ages like this

    names[0], ages[0]
    

1 Comment

Better with a genexpr than a listcomp. No point building an extra list for no reason. But otherwise, I was writing the exact same thing (I hesitated over the genexpr vs. map choice and you beat me to it).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.