Results 1 to 3 of 3

Thread: creating a temporary file in python3

  1. #1
    Join Date
    Jan 2012
    Beans
    161

    creating a temporary file in python3

    Code:
    import tempfile
    a = tempfile.TemporaryFile(prefix='myfile',suffix='tmp')
    
    >>> a.write('hello temp world')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: 'str' does not support the buffer interface
    what do i need to do so that i can write to the tempfile? The documentation says that the default mode is sufficient......

  2. #2
    Join Date
    Aug 2010
    Location
    Lancs, United Kingdom
    Beans
    1,588
    Distro
    Ubuntu Mate 16.04 Xenial Xerus

    Re: creating a temporary file in python3

    This is to do with Unicode strings versus bytes strings. You need
    Code:
    a.write(b'hello temp world')

  3. #3
    Join Date
    Apr 2009
    Location
    Germany
    Beans
    2,134
    Distro
    Ubuntu Development Release

    Re: creating a temporary file in python3

    its better to be explicit about the encoding:
    Code:
    a.write('hello temp world'.encode("UTF-8"))
    just casting to bytes will fail if the string does not only contain ascii (which it can in python3).
    Last edited by MadCow108; October 3rd, 2013 at 11:31 PM.

Tags for this Thread

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •