3

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.

1
  • 3
    The question is not about learning how to write a string to disk. So your purpose in transforming a string to a file would be to exploit some property or behavior specific to a file and not found (or easily emulated) with a string. If so, which properties/behaviors? If not, what is this about ? Commented Oct 15, 2009 at 4:17

2 Answers 2

15

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.