读取具有指定换行符分隔符的文件 [英] Reading a file with a specified delimiter for newline

查看:34
本文介绍了读取具有指定换行符分隔符的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,其中的行使用分隔符分隔,比如 ..我想一行一行地读取这个文件,其中的行应该基于 . 而不是换行符的存在.

I have a file in which lines are separated using a delimeter say .. I want to read this file line by line, where lines should be based on presence of . instead of newline.

一种方法是:

f = open('file','r')
for line in f.read().strip().split('.'):
   #....do some work
f.close()

但是如果我的文件太大,这会降低内存效率.我想逐行阅读,而不是一起阅读整个文件.

But this is not memory efficient if my file is too large. Instead of reading a whole file together I want to read it line by line.

open 支持参数 'newline' 但这个参数只需要 None, '', ' ', ' ', and ' ' 作为提到的输入这里.

open supports a parameter 'newline' but this parameter only takes None, '', ' ', ' ', and ' ' as input as mentioned here.

有没有什么方法可以有效地读取文件行但基于预先指定的分隔符?

推荐答案

您可以使用生成器:

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

这篇关于读取具有指定换行符分隔符的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆