Python IO programming--stringio & Bytesio

Source: Internet
Author: User

1.1   Stringio & BytesIO1.1.1   Stringio

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

Write Stringio

>>> Fromio Import Stringio

>>> f = Stringio ()

>>> f.write (' Hello ')

5

>>> F.write (")

1

>>> f.write (' world! ')

6

>>> f.getvalue ()

' Hello world! '

>>> print (F.getvalue ())

Hello world!

Read Stringio

>>> from IO import Stringio

>>> f = Stringio (' Xiongxiong\nlove\ndaidai ')

>>> while True:

... s = f.readline () # is not the same as the readlines of the read file

... if s = = ":

... break

... print (S.strip ())

...

Xiongxiong

Love

Daidai

1.1.2   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 andthen write some bytes:

>>> from IO import Bytesio

>>> f = Bytesio ()

>>> f.write (' Chinese ' encode (' utf-8 '))

6

>>> print (F.getvalue ())

B ' \xe4\xb8\xad\xe6\x96\x87 '

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

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

>>> from IO import Stringio

>>> F =bytesio (b ' \xe4\xb8\xad\xe6\x96\x87 ')

>>> F.read ()

B ' \xe4\xb8\xad\xe6\x96\x87 '


This article is from the "90SirDB" blog, be sure to keep this source http://90sirdb.blog.51cto.com/8713279/1826524

Python IO programming--stringio & 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.