Abh*_*pta 14 python io file-io python-2.7
我有一个文件,其中使用分隔符分隔行..我想逐行阅读这个文件,其中的行应该基于存在.而不是换行.
一种方法是:
f = open('file','r')
for line in f.read().strip().split('.'):
#....do some work
f.close()
Run Code Online (Sandbox Code Playgroud)
但如果我的文件太大,这不是内存效率.我没有一起阅读整个文件,而是想逐行阅读.
open支持参数'newline',但此参数仅None, '', '\n', '\r', and '\r\n'作为此处提到的输入.
有没有办法有效地读取文件行但是基于预先指定的分隔符?
NPE*_*NPE 20
你可以使用一个发电机:
def myreadlines(f, newline):
buf = ""
while True:
while newline in buf:
pos = buf.index(newline)
yield buf[:pos]
buf = buf[pos + len(newline):]
chunk = f.read(4096)
if not chunk:
yield buf
break
buf += chunk
with open('file') as f:
for line in myreadlines(f, "."):
print line
Run Code Online (Sandbox Code Playgroud)