mkstemp on pre-2.3 Python

Nick Craig-Wood nick at craig-wood.com
Fri Nov 19 09:30:04 EST 2004


djw <donald.welch at hp.com> wrote:
>  Hi, c.l.p'ers-
> 
>  I working on some code that creates a temporary file on Linux. I found some
>  code that the BDFL posted previously on the newsgroup and adapted it for my
>  use. I can't get the "pre-2.3" code to work.
> 
> 
>  try:
>      make_temp_file = tempfile.mkstemp # 2.3+
>  except AttributeError: 
>      def make_temp_file( suffix='', prefix='', dir='', text=False ): #pre-2.3
>          path = tempfile.mktemp( suffix ) 
>          fd = os.open( path, os.O_WRONLY|os.O_CREAT|os.O_EXCL, 0700 )
>          os.unlink( path )
>          return ( os.fdopen( fd, 'w+b' ), path ) 
> 
> 
> 
>  Here's the error:
> 
>  File "utils.py", line 583, in make_temp_file
>      return ( os.fdopen( fd, 'w+b' ), path )
>  OSError: [Errno 22] Invalid argument
> 
>  Anybody have any ideas on what I am doing wrong?

Replace the os.O_WRONLY with os.O_RDWR and all will be fine

>>> import tempfile, os
>>> suffix=""
>>> path = tempfile.mktemp( suffix )
>>> fd = os.open( path, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0700 )
>>> f = os.fdopen( fd, 'w+b' )
>>> f
<open file '<fdopen>', mode 'w+b' at 0xb7de7a60>
>>> print >>f, "Hello"
>>> f.seek(0)
>>> f.read()
'Hello\n'
>>> f.close()

-- 
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick



More information about the Python-list mailing list