Search code examples
pythonstringlinecache

How to get three integers from a specific line in a file with Python?


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.


Solution

  • 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]