9
\$\begingroup\$

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 
\$\endgroup\$

1 Answer 1

16
\$\begingroup\$

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.)

\$\endgroup\$
1
  • \$\begingroup\$ Thx for your answer :) I didn't think of using map here. \$\endgroup\$ Commented Jun 11, 2012 at 6:02

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.