<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # StringIO和BytesIO ## StringIO 很多時候,數據讀寫不一定是文件,也可以在內存中讀寫。 StringIO顧名思義就是在內存中讀寫str。 要把str寫入StringIO,我們需要先創建一個StringIO,然后,像文件一樣寫入即可: ``` >>> from io import StringIO >>> f = StringIO() >>> f.write('hello') 5 >>> f.write(' ') 1 >>> f.write('world!') 6 >>> print(f.getvalue()) hello world! ``` `getvalue()`方法用于獲得寫入后的str。 要讀取StringIO,可以用一個str初始化StringIO,然后,像讀文件一樣讀取: ``` >>> from io import StringIO >>> f = StringIO('Hello!\nHi!\nGoodbye!') >>> while True: ... s = f.readline() ... if s == '': ... break ... print(s.strip()) ... Hello! Hi! Goodbye! ``` ## BytesIO StringIO操作的只能是str,如果要操作二進制數據,就需要使用BytesIO。 BytesIO實現了在內存中讀寫bytes,我們創建一個BytesIO,然后寫入一些bytes: ``` >>> from io import BytesIO >>> f = BytesIO() >>> f.write('中文'.encode('utf-8')) 6 >>> print(f.getvalue()) b'\xe4\xb8\xad\xe6\x96\x87' ``` 請注意,寫入的不是str,而是經過UTF-8編碼的bytes。 和StringIO類似,可以用一個bytes初始化BytesIO,然后,像讀文件一樣讀取: ``` >>> from io import StringIO >>> f = BytesIO(b'\xe4\xb8\xad\xe6\x96\x87') >>> f.read() b'\xe4\xb8\xad\xe6\x96\x87' ``` ## 小結 StringIO和BytesIO是在內存中操作str和bytes的方法,使得和讀寫文件具有一致的接口。 ## 參考源碼 [do_stringio.py](https://github.com/michaelliao/learn-python3/blob/master/samples/io/do_stringio.py) [do_bytesio.py](https://github.com/michaelliao/learn-python3/blob/master/samples/io/do_bytesio.py)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看