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