Best method for reading newline delimited files and discarding the newlines?

solarce picture solarce · Feb 13, 2009 · Viewed 107.8k times · Source

I am trying to determine the best way to handle getting rid of newlines when reading in newline delimited files in Python.

What I've come up with is the following code, include throwaway code to test.

import os

def getfile(filename,results):
   f = open(filename)
   filecontents = f.readlines()
   for line in filecontents:
     foo = line.strip('\n')
     results.append(foo)
   return results

blahblah = []

getfile('/tmp/foo',blahblah)

for x in blahblah:
    print x

Suggestions?

Answer

Curt Hagenlocher picture Curt Hagenlocher · Feb 13, 2009
lines = open(filename).read().splitlines()