开发者

In Python, how do I transform a string into a file?

开发者 https://www.devze.com 2022-12-08 19:11 出处:网络
There is a read-only library function that takes a file as an argument. But 开发者_开发问答I have a string.

There is a read-only library function that takes a file as an argument. But 开发者_开发问答I have a string.

How do I convert a string to a file, that if you read the file it will return this string? I don't want to write to disk.


The StringIO module:

>>> import StringIO
>>> f = StringIO.StringIO("foo")
>>> f.read()
'foo'

The cStringIO module has the same interface, and is faster, but can't deal with Unicode strings that have non-ASCII characters.

StringIO documentation


what do you want? if you want to read from file just use:

file('/path/to/file').read()

or

open('/path/to/file','r').read()

if you want to read string,just do as suggest by Phil

0

精彩评论

暂无评论...
验证码 换一张
取 消