读取换行符分隔文件和丢弃换行符的最佳方法?

sol*_*rce 82 python file readline

我正在尝试确定在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
Run Code Online (Sandbox Code Playgroud)

建议?

Cur*_*her 192

lines = open(filename).read().splitlines()
Run Code Online (Sandbox Code Playgroud)

  • 使用CPython,文件对象的引用计数将在不再使用时变为零,文件将自动关闭.对于纯粹的GC实现,如Jython和IronPython,文件可能在GC运行之前不会关闭 - 因此这种简洁的变化可能不是最佳的. (6认同)
  • 临时文件是否会在此代码中关闭? (4认同)
  • 在带有8GB RAM的Mac OS X 10.7.5上,我可以读取高达2047MB的文件(我的定义:1 MB = 1024 x 1024字节).2048MB将抛出MemoryError异常. (2认同)

小智 23

这是一台能满足您要求的发电机.在这种情况下,使用rstrip足够并且比strip快一点.

lines = (line.rstrip('\n') for line in open(filename))
Run Code Online (Sandbox Code Playgroud)

但是,您很可能也希望使用它来摆脱尾随空格.

lines = (line.rstrip() for line in open(filename))
Run Code Online (Sandbox Code Playgroud)

  • @andrewb Using()给出了一个生成器表达式,它不使用[](列表推导)那么多的内存. (8认同)

Paw*_*żak 9

您如何看待这种方法?

with open(filename) as data:
    datalines = (line.rstrip('\r\n') for line in data)
    for line in datalines:
        ...do something awesome...
Run Code Online (Sandbox Code Playgroud)

生成器表达式避免将整个文件加载到内存中并with确保关闭文件


Dav*_*d Z 8

for line in file('/tmp/foo'):
    print line.strip('\n')
Run Code Online (Sandbox Code Playgroud)