Python Learning Notes (24) Stringio and Bytesio

Source: Internet
Author: User

Stringio

Most of the time, data read and write is not necessarily a file, but also can read and write in memory .

Stringio, as the name implies, reads and writes STR in memory.

To write Str to Stringio, we need to create a stringio and then write it like a file:

  >>> from  io import   Stringio  >>> f = >>> f.write ( hello   " )  5>>> F.write ( '   '  )  1>>> F.write ( Span style= "color: #800000;" > '  

getvalue()method is used to obtain the post-write Str.

To read Stringio, you can initialize the Stringio with a STR and then read it like a read file:

 from Import Stringio>>> f = Stringio ('hello!\nhi!\ngoodbye! ' ) while True     : ... = F.readline ()      ... if "' :...           Break ...      Print (S.strip ()) ... Hello! Hi! goodbye!
Bytesio

Stringio operation can only be str, if you want to manipulate binary data , you need to use Bytesio.

Bytesio implements read-write bytes in memory, we create a bytesio and then write some bytes:

 from Import Bytesio>>> f = Bytesio ()>>> f.write (' Chinese '. Encode ( ' Utf-8 ' )print(F.getvalue ()) b'\xe4\xb8\xad\xe6\x96\x87' 

Note that the write is not str, but the UTF-8 encoded bytes.

Similar to Stringio, you can initialize the Bytesio with a bytes, and then read like a read file :

 from Import Bytesio>>> f = bytesio (b'\xe4\xb8\xad\xe6\x96\x87')> >> f.read () b'\xe4\xb8\xad\xe6\x96\x87'
Summary

Stringio and Bytesio are methods of operating str and bytes in memory, allowing for a consistent interface to read and write files.

Python Learning Notes (24) Stringio and Bytesio

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.