Reading a file with a specified delimiter for newline

后端 未结 3 1869
遇见更好的自我
遇见更好的自我 2020-12-01 12:43

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 .

3条回答
  •  余生分开走
    2020-12-01 13:22

    You could use a generator:

    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
    

提交回复
热议问题