Quantcast
Viewing latest article 2
Browse Latest Browse All 5

Answer by 9716278 for Reopening a closed stringIO object in Python 3

When you f.close() you remove it from memory. You're basically doing a deref x, call x; you're looking for a memory location that doesn't exist.

Here is what you could do in stead:

import ioa = 'Me, you and them\n'f = io.StringIO(a)f.read(1)f.close()# Put the text form a without the first char into StringIO.p = io.StringIO(a[1:]).# do some work with p.

I think your confusion comes form thinking of io.StringIO as a file on the block device. If you used open() and not StringIO, then you would be correct in your example and you could reopen the file. StringIO is not a file. It's the idea of a file object in memory. A file object does have a StringIO, but It also exists physically on the block device. A StringIO is just a buffer, a staging area in memory of the data with in it. When you call open() a buffer is created, but there is still the data on block device.

Perhaps this is more what you want

fo = open('f.txt','w+')fo.write('Me, you and them\n')fo.read(1)fo.close()# reopen the now closed file `f`p = open('f.txt','r')# do stuff with pp.close()

Here we are writing the string to the block device, so that when we close the file, the information written to it will remain after it's closed. Because this is creating a file in the directory the progarm is run in, it may be a good idea to give the file an extension. For example, you could name the file f.txt instead of f.


Viewing latest article 2
Browse Latest Browse All 5

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>