1

I want to change the def a to close the handle that is opened by mkstemp. But I failed.

handle.close() leads to erros because handle is just an int...

del handle also does not change the behaviour

MWE:

import tempfile
import codecs 

def a(json_content):
    handle, file = tempfile.mkstemp(prefix="foobar-",suffix=".json")
    write_to_file(json_content, file)

def write_to_file(text, filename):
    with codecs.open(filename, 'w', 'utf-8', errors='ignore') as fp:
        fp.write(unicode(text))

if __name__ == '__main__':
    for i in range(50000):
        a('{"foo":"bar", "iteration":%s}' %(i))

I use anaconda python 2.7.13 with windows (if thats making a difference)

helt
  • 4,925
  • 3
  • 35
  • 54

1 Answers1

2

Use os.close to close a file represented by a file descriptor:

os.close(handle)
donkopotamus
  • 22,114
  • 2
  • 48
  • 60