I have to list a integers from a text file separated by newlines into a python list. I ended up with the code above which works (for my case) but certainly is far form optimal.

def readIntegers(pathToFile):

    f = open(pathToFile)
    contents = f.read()
    f.close()

    tmpStr = ""

    integers = []

    for char in contents:

        if char == '\r':
            integers.append(int(tmpStr))
            tmpStr = ""
            continue

        if char == '\n':
            continue

        tmpStr += char

    return integers

Now I have much less code, but I'm not sure for which cases split() works correctly.

def readIntegers(pathToFile):

    with open(pathToFile) as f:
        a = [int(x) for x in f.read().split()]
    return a
share|improve this question

2 Answers

up vote 8 down vote accepted

No need for split (you can use readlines). But no need for readlines, for that matter:

def read_integers(filename):
    with open(filename) as f:
        return map(int, f)

or, if that’s more to your fancy:

def read_integers(filename):
    with open(filename) as f:
        return [int(x) for x in f]

A file object is simply iterable in Python, and iterates over its lines.

Note that, contrary to what I said earlier, wrapping the file object in a with block is highly recommended. Python doesn’t actually guarantee (although it recommends it) that objects are disposed of automatically at the end of the scope. Worse, it’s not guaranteed that a file object that is collected actually closes the underlying stream.

(Note that I’ve adapted the method name to Python conventions.)

share|improve this answer
Thx for your answer :) I didn't think of using map here. – Nils Jun 11 '12 at 6:02

A bit faster version:

def readIntegers(filename):
    return map(int, open(filename).read().split())
share|improve this answer
Cool, what if I wanted to skip parsing anything that is not an integer? – Leonid Jun 10 '12 at 19:29
1  
Didn't get it - is it a new question? :) If you want to extract integers ony - use the re.findall('\d+', open(filename).read().split()) – cat_baxter Jun 10 '12 at 19:49
3  
It is not recommended that you simply open() files, without explicitly close()ing them afterwards. Adding a with clause to your answer would make it an ideal solution. – Joel Cornett Jun 10 '12 at 20:50
@Joel I’m slightly baffled. Apart from the with block remark which is true, what makes this answer better than mine in your opinion? Isn’t read().split() both unnecessary and potentially inefficient? – Konrad Rudolph Jun 12 '12 at 10:19
@KonradRudolph: I actually didn't read your solution until just now. I was merely informing cat_baxter know about the explicit closing. Now that I have read your solution, I'll +1 it. – Joel Cornett Jun 12 '12 at 17:20

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.