Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python readline() from a string?

Tags:

python

In python, is there a built-in way to do a readline() on string? I have a large chunk of data and want to strip off just the first couple lines w/o doing split() on the whole string.

Hypothetical example:

def handleMessage(msg):    headerTo  = msg.readline()    headerFrom= msg.readline()    sendMessage(headerTo,headerFrom,msg)  msg = "Bob Smith\nJane Doe\nJane,\nPlease order more widgets\nThanks,\nBob\n" handleMessage(msg) 

I want this to result in: sendMessage("Bob Smith", "Jane Doe", "Jane,\nPlease order...")

I know it would be fairly easy to write a class that does this, but I'm looking for something built-in if possible.

EDIT: Python v2.7

like image 368
Brian McFarland Avatar asked Sep 19 '11 14:09

Brian McFarland


People also ask

How do you read each line of a string in Python?

Method 1: Read a File Line by Line using readlines() readlines() is used to read all the lines at a single go and then return them as each line a string element in a list. This function can be used for small files, as it reads the whole file content to the memory, then split it into separate lines.

Does readline () return a string?

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 Python readline () do?

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.


2 Answers

In Python 3, you can use io.StringIO:

>>> msg = "Bob Smith\nJane Doe\nJane,\nPlease order more widgets\nThanks,\nBob\n" >>> msg 'Bob Smith\nJane Doe\nJane,\nPlease order more widgets\nThanks,\nBob\n' >>> >>> import io >>> buf = io.StringIO(msg) >>> buf.readline() 'Bob Smith\n' >>> buf.readline() 'Jane Doe\n' >>> len(buf.read()) 44 

In Python 2, you can use StringIO (or cStringIO if performance is important):

>>> import StringIO >>> buf = StringIO.StringIO(msg) >>> buf.readline() 'Bob Smith\n' >>> buf.readline() 'Jane Doe\n' 
like image 167
jterrace Avatar answered Oct 30 '22 06:10

jterrace


The easiest way for both python 2 and 3 is using string's method splitlines(). This returns a list of lines.

>>> "some\nmultilene\nstring\n".splitlines() 

['some', 'multilene', 'string']

like image 44
Mario Wanka Avatar answered Oct 30 '22 06:10

Mario Wanka