creating stream to iterate over from string in Python -


I want to create a stream from a string in Python so that it is similar to reading the string, as it reads from a text File goes In the open ('myfile.txt')

 : print line  

The contents of 'myfile.txt' are stored in a string < Code> s . Is this the right / best way?

Pre line

I want to create a dragon with a string so that it is equivalent to reading the string as if it is read from a text file .

Is this the right / best way to do this?

Yes, unless you really want this to be a list.

If this line intends to consume the line, then the way you are doing it is understandable.

StringIO () creates a file like object

is a method in file objects, .readlines () , Which executes the object as a list. Instead of making the data physical in the list, you can repeat it again, which is more memory light:

  # from StringIO import StringIO # Python 2 import from IO import StringIO # python 3 import Txt = "foo \ nbar \ nbaz"  

Here we add a list to a line , so that we can resize on the object like the file And can handle a handle on the data (more efficient list (file_like_io) .

  m_1 = [] file_like_io = string for stringio (txt) line E_like_io: m_1.append (line)  

and now:

  gt; m_1 ['foo \ n', 'bar \ n ',' Baz ']  

You can :

  & gt; & gt; file_like_io.seek (0) & gt; You can return your IO to any index point with.; & Gt; file_like_io.tell () # print where we are now in the object 0  

If you actually list it In

.readlines () is assumed to be in the form of a stringio as an iterator, such as a list (io) - It is considered less better.

  & gt; & Gt; M_2 = file_like_io.readlines ()  

And we can see that our results are the same:

  & gt; & Gt; & Gt; Keep in mind that it is going to be distributed after new lines, also saves them in the form of text, so you will get two new lines for each print line, ng on double-spice print. 


Comments

Popular posts from this blog

ios - How do I use CFArrayRef in Swift? -

eclipse plugin - Run java code error: Workspace is closed -

c - Error on building source code in VC 6 -