Is it possible to change the newline character the .readline()
method looks for while reading lines? I might have the need to read a stream from a file object that will be delimited in something other than newlines and it could be handy to get a chunk at a time. file
objects don't have a readuntil
which I wouldn't have to create if I can use readline
EDIT:
I haven't yet tried it on a pipe other than stdin
; but this seems to work.
class cfile(file):
def __init__(self, *args):
file.__init__(self, *args)
def readuntil(self, char):
buf = bytearray()
while True:
rchar = self.read(1)
buf += rchar
if rchar == char:
return str(buf)
usage:
>>> import test
>>> tfile = test.cfile('/proc/self/fd/0', 'r')
>>> tfile.readuntil('0')
this line has no char zero
this one doesn't either,
this one does though, 0
"this line has no char zero\nthis one doesn't either,\nthis one does though, 0"
>>>
The readline method reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end.
Python File readline() Method The readline() method returns one line from the file. You can also specified how many bytes from the line to return, by using the size parameter.
Python File readlines() Method The readlines() method returns a list containing each line in the file as a list item.
The new line character in Python is \n . It is used to indicate the end of a line of text.
No.
Consider creating a generator using file.read()
and yielding chunks delimited by given character.
Edit:
The sample you provided should work just fine. I would prefer to use a generator though:
def chunks(file, delim='\n'):
buf = bytearray(),
while True:
c = self.read(1)
if c == '': return
buf += c
if c == delim:
yield str(buf)
buf = bytearray()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With