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)
小智 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)
您如何看待这种方法?
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
确保关闭文件
归档时间: |
|
查看次数: |
99716 次 |
最近记录: |