0

I have a (ASCII) file, foo.txt, which has a lot of stuff in it but I only care about the three numbers on line 2 (separated by white space). For your information (I don't know if it will be relevant) the number of columns on the lines before and after this line aren't the same as for line 2.

I want to take these three numbers from line 2 and store them as three separate integers (whether three separate variables or a list of length 3 I don't care).

I was using linecache.getline() to get that line specifically from the file but it pulls the line out as one long string (rather than having each number on the line be its own string) and I don't know how to extract the three numbers from the resultant string.

Here is my code:

import linecache
linetemp = linecache.getline('foo.txt',2)
#nr = [int(i) for i in line.split(linetemp)]
print nr

The commented line was my attempt at extracting the numbers in linetemp as integers but since linetemp is one string (rather than a list of strings) it doesn't work.

If you can improve on what I have above using linecache.getline() or if you have another method to pull the three numbers from line 2 of foo.txt I will be happy either way.

NeutronStar
  • 2,057
  • 7
  • 31
  • 49

2 Answers2

3

Try

nr = [int(i) for i in linetemp.split()]

You need to call the split() function on the string you want to split.

Example:

In [1]: linetemp = '  12     27   435'

In [2]: nr = [int(i) for i in linetemp.split()]

In [3]: nr
Out[3]: [12, 27, 435]
MattDMo
  • 100,794
  • 21
  • 241
  • 231
1

I wouldn't bother using linecache here - that's meant for other purposes - instead use an islice to limit over the range of the file you're reading, then convert that line to ints:

from itertools import islice

with open('foo.txt') as fin:
    line2 = next(islice(fin, 1, None), '')
    nr = [int(word) for word in line2.split()]

If you don't want an import, then you can do:

with open('foo.txt') as fin:
    next(fin, '') # skip first line
                                # next line or blank
    nr = [int(word) for word in next(fin, '').split()]
Jon Clements
  • 138,671
  • 33
  • 247
  • 280