开发者社区> 问答> 正文

字符串的I/O操作

你想使用操作类文件对象的程序来操作文本或二进制字符串。

展开
收起
哦哦喔 2020-04-17 12:23:58 950 0
1 条回答
写回答
取消 提交回答
  • 使用 io.StringIO() 和 io.BytesIO() 类来创建类文件对象操作字符串数据。比如:
    
    >>> s = io.StringIO()
    >>> s.write('Hello World\n')
    12
    >>> print('This is a test', file=s)
    15
    >>> # Get all of the data written so far
    >>> s.getvalue()
    'Hello World\nThis is a test\n'
    >>>
    
    >>> # Wrap a file interface around an existing string
    >>> s = io.StringIO('Hello\nWorld\n')
    >>> s.read(4)
    'Hell'
    >>> s.read()
    'o\nWorld\n'
    >>>
    io.StringIO 只能用于文本。如果你要操作二进制数据,要使用 io.BytesIO 类来代替。比如:
    
    >>> s = io.BytesIO()
    >>> s.write(b'binary data')
    >>> s.getvalue()
    b'binary data'
    >>>
    
    2020-04-17 12:24:09
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载