Skip to content

Python:io

스트림 작업을 위한 핵심 도구

StringIO

Write Data To StringIO Object

# import StringIO module.
>>> from io import StringIO
# Create a StringIO object.
>>> strIO = StringIO()
>>> strIO.write('Good')
4
>>> strIO.write(' Morning!')
9
# getvalue method will return the written string.
>>> print(strIO.getvalue())
Good Morning!

Read Data From StringIO Object

# Import StringIO module.
>>> from io import StringIO
# Create a new StringIO object.
>>> strIO = StringIO('Hello \nWorld!')
# Loop and read each line of the StringIO object.
>>> while True:
# Read one line.
... line = strIO.readline()
# If reach the end of the data then jump out of the loop.
... if line == '':
... break
# Print the tripped line data.
... print(line.strip())
...
Hello
World!

BytesIO

버퍼 길이 알아내기

def get_buffer_size(buffer: BytesIO) -> int:
    """
    Size remaining in the buffer.

    Performance tip:
        * `timeit.timeit(buffer.tell)` -> 0.083s
        * `timeit.timeit(buffer.getbuffer)` -> 0.146s
        * `timeit.timeit(buffer.getvalue)` -> 0.028s
    """
    return len(buffer.getvalue())

Write Bytes Data To ByteIO Object

# Import BytesIO module.
>>> from io import BytesIO
# Create a BytesIO object.
>>> bytIO = BytesIO()
# Write bytes that are utf-8 encoded chine word.
>>> bytIO.write('中文'.encode('utf-8'))
6
# Get the value and print.
>>> print(bytIO.getvalue())
# The value is byte charactor not a string.
b'\xe4\xb8\xad\xe6\x96\x87'

Read Bytes Data From ByteIO Object

>>> from io import BytesIO
>>> byteIOObj = BytesIO()
>>> byteIOObj.write('你好'.encode('utf-8'))
byteIOObj.read()
b'\xe4\xb8\xad\xe6\x96\x87'

See also

Favorite site