0

https://docs.python.org/3.7/library/io.html#text-i-o says that io.Stringio is created inside of an open() file object. If I want to start with a Stringio and then flush it into a file object how would I do that? Obviously I could just open the new file object and then write the Stringio to the object, but is there a cleaner way?

from io import *

buf = StringIO() 
buf.write('here is my text in stringio')
buf.flush('filename')
buf.close()

Other than

buf = StringIO() 
buf.write('here is my text in stringio')
with open('filename', 'w') as fo:
    buf.seek(0)
    fo.write(buf.read())
buf.close()

is there a way to do this?

9716278
  • 2,044
  • 2
  • 14
  • 30
  • May I ask why? The entire point of `StringIO` is to fake a file object. If you know you are going to work with an actual file, why bother with `StringIO` to begin with? – DeepSpace Nov 14 '19 at 11:12
  • @DeepSpace I have a part of a program set up to write to a file, but I also need it's out put for `_io.TextIOWrapper`, so if I can generalize the function that feeds both I don't have to worry about creating a file to keep the function happy when it might just be sent to TextIO anyway. I then won't have to delete the make function happy file either. – 9716278 Nov 14 '19 at 12:59

0 Answers0