我正在尝试确定在Python中读取换行符分隔文件时处理删除换行符的最佳方法.
我想出的是以下代码,包括要测试的一次性代码.
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
建议?
lines = open(filename).read().splitlines()
这是一台能满足您要求的发电机.在这种情况下,使用rstrip足够并且比strip快一点.
lines = (line.rstrip('\n') for line in open(filename))
但是,您很可能也希望使用它来摆脱尾随空格.
lines = (line.rstrip() for line in open(filename))
您如何看待这种方法?
with open(filename) as data: datalines = (line.rstrip('\r\n') for line in data) for line in datalines: ...do something awesome...
生成器表达式避免将整个文件加载到内存中并with
确保关闭文件
for line in file('/tmp/foo'): print line.strip('\n')