0

I have a file with multiple lines and right now I read 20480 bytes at once:

while True:
    data = fh.read(20480)
    if data == '':
        fh.close()
        break

I have another file where ETX is used as the delimiter. How do I read characters till ETX is reached?

Thanks in advance!

NoName
  • 1,509
  • 2
  • 20
  • 36

1 Answers1

0

Assuming that you want to read multiple records, each delimited by ASCII 3, then the myreadlines function in this answer will do the trick.

The only difference is using the character with value 3 as the delimiter, instead of period, like this:

delim = chr(3)
with open('file') as f:
 for line in myreadlines(f, delim):
  print line
Community
  • 1
  • 1
MassPikeMike
  • 672
  • 3
  • 12
  • Thank you for your answer. Can you please let me know why 4096 bytes are being read in this function: `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` – NoName Mar 23 '17 at 19:53
  • I think there is nothing special about the value 4096 (it is just a common block size) and another value would work equally well. – MassPikeMike Mar 23 '17 at 21:45