Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change newline character .readline() seeks

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"
>>>
like image 601
tMC Avatar asked Jun 08 '11 19:06

tMC


People also ask

Does readline () take in the \n at the end of line?

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.

What does readline () do in Python?

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.

What is the return type of the readline () method?

Python File readlines() Method The readlines() method returns a list containing each line in the file as a list item.

How do you read a new line character in Python?

The new line character in Python is \n . It is used to indicate the end of a line of text.


1 Answers

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()
like image 189
pajton Avatar answered Oct 09 '22 18:10

pajton