Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Wrap string thành file object trong Python

Để tạo file-like object (duck type như File) với nội dung string, dùng module StringIO. Truyền string vào constructor của StringIO rồi dùng như file object. Ví dụ:

>>> from cStringIO import StringIO
>>> f = StringIO('Hello world')
>>> f.read()
'Hello world'

Python 3 dùng module io. Ví dụ:

>>> import io
>>> f = io.StringIO('Hello world')
>>> f.read()
'Hello world'

Lưu ý: StringIO không chấp nhận Unicode string không encode được thành plain ASCII string.