@contextmanager
def ensure_clean(filename=None, return_filelike=False):
 filename = (filename or '')
 fd = None
 if return_filelike:
  f = tempfile.TemporaryFile(suffix=filename)
  try:
   (yield f)
  finally:
   f.close()
 else:
  if len(os.path.dirname(filename)):
   raise ValueError("Can't pass a qualified name to ensure_clean()")
  try:
   (fd, filename) = tempfile.mkstemp(suffix=filename)
  except UnicodeEncodeError:
   import nose
   raise nose.SkipTest('no unicode file names on this system')
  try:
   (yield filename)
  finally:
   try:
    os.close(fd)
   except Exception as e:
    print ("Couldn't close file descriptor: %d (file: %s)" % (fd, filename))
   try:
    if os.path.exists(filename):
     os.remove(filename)
   except Exception as e:
    print ('Exception on removing file: %s' % e)

@ contextmanager def ensure_clean ( filename = None , return_filelike = False ) : filename = ( filename or '' ) fd = None if return_filelike : f = tempfile . TemporaryFile ( suffix = filename ) try : ( yield f ) finally : f . close ( ) else : if len ( os . path . dirname ( filename ) ) : raise ValueError ( "Can't pass a qualified name to ensure_clean()" ) try : ( fd , filename ) = tempfile . mkstemp ( suffix = filename ) except UnicodeEncodeError : import nose raise nose . SkipTest ( 'no unicode file names on this system' ) try : ( yield filename ) finally : try : os . close ( fd ) except Exception as e : print ( "Couldn't close file descriptor: %d (file: %s)" % ( fd , filename ) ) try : if os . path . exists ( filename ) : os . remove ( filename ) except Exception as e : print ( 'Exception on removing file: %s' % e )
gets a temporary path and agrees to remove on close .