Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 981
solarce Avatar asked Feb 13 '09 06:02

solarce


2 Answers

lines = open(filename).read().splitlines() 
like image 171
Curt Hagenlocher Avatar answered Oct 13 '22 18:10

Curt Hagenlocher


Here's a generator that does what you requested. In this case, using rstrip is sufficient and slightly faster than strip.

lines = (line.rstrip('\n') for line in open(filename)) 

However, you'll most likely want to use this to get rid of trailing whitespaces too.

lines = (line.rstrip() for line in open(filename)) 
like image 23
TimoLinna Avatar answered Oct 13 '22 16:10

TimoLinna