1

I´m a total newbie

infile:

Baby    1902
Buby    1952
Boby    1950
Daisy   1990
Dassy   1940
Dasay   1960
Rob 1960
Bob 1990
Bolob   1970
Asdf    1999

Code:

#!/usr/bin/python

inData = open('crap3.txt')
Lina = inData.readline()
Lina = Lina.strip()
tmpFields = Lina.split('\t')
for line in inData:
  bla = tmpFields[1]
  print(bla)

It prints out the first birthyear ten times. I would like it to print out every year.

1
  • Refer to PEP 8 for the proper way to style Python code (Lina should not be capitalized, 4 spaces for indentation, etc). It makes your code much easier to read when you follow the style guide. Commented Jan 5, 2012 at 14:28

4 Answers 4

8

Try this:

with open('crap3.txt') as inData:
    for line in inData:
        line = line.strip()
        name, year = line.split('\t', 1)
        print(year)

It's good custom to use with when opening files. The file is then automatically closed at the end of the block.

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

Comments

4

Move the split inside the loop, so that it's done for every line. The following suffices as your complete program:

inData = open("crap3.txt")
for line in inData:
    print(line.split()[1])

Comments

0

You aren't doing anything with the line variable in the loop. Try this:

lines = open('crap3.txt').readlines()
for line in lines:
    bits = line.split('\t')
    print bits[0]

Comments

0

readline read only one line. This way you iterate over the same line again and again.

use inData.readlines() or put the readline into your loop ;)

Comments

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.