2

Use case:
I have a method doSomething(file) which accepts the file object and does something, I can't alter this method.

Now, to have the file to pass to doSomething, i need to open it through open() method but i don't have that file to store on localhost and i am allowed to but i have the file contents and file name stored in python variables. Is there a way to get file object from these two variables ?

2 Answers 2

2

The StringIO class is a file-like class, which stores the contents in memory. You can create an instance with your content, and pass it to doSomething(strio).

From the docs:

import StringIO

output = StringIO.StringIO()
output.write('First line.\n')
print >>output, 'Second line.'
Sign up to request clarification or add additional context in comments.

1 Comment

Note that you will need to use output.seek(0) after writing or the function that gets the file-like object will have the offset after the last write rather than at the start of the file-like object.
0

If your data is 8-bit string or Unicode, StringIO is a good option. However if your data is binary or mix of 8-bit string and Unicode, then StringIO will fail. BytesIO is the recommended option in this case.

import io

your_data = b'\x02\x1b\x92\x1fs\x96\x97\xe8\x01'
sd = io.BytesIO()
sd.write(your_data)
sd.seek(0) # Seek to the beginning

# sd can act like a file handle. Pass it to your function. 

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.