1

I have been trying to write variables to a temporary text file but I get the following error:

Traceback (most recent call last):
  File "F:/A453/_Codes_/APP CONFIG/Temp.py", line 102, in <module>
    ORXQC-IIHL2-6AV55-FIJEV-2""")
  File "C:\Program Files (x86)\Python34\lib\tempfile.py", line 399, in     func_wrapper
    return func(*args, **kwargs)
TypeError: 'str' does not support the buffer interface

My Script is the Following:

import tempfile
TEMPDIR=tempfile.TemporaryFile()
TEMPDIR.write("""B5IB6-ELAZ1-RAPY9-V8X1I-3
OKXVB-Q8B9G-IT9ZF-MI4EQ-2
PLDZ6-769YT-YJSR4-682JT-7
H67L5-9HO4C-4UDSR-BYA14-6
Y73EC-S8OJG-O1APH-N41KM-3
JCYVV-UXNIN-9RGSU-WQ9SD-1
WL9AO-9BLI7-GXXGM-VESEU-2
VDLHT-IXMUY-V4FPU-V3IFZ-1
8CPVN-Z776Z-Y49J3-2C683-5
ORXQC-IIHL2-6AV55-FIJEV-2""")
Activation=input('Please Enter your Product Activation Key: ')
if Activation in TEMPDIR:
    print('True')
else:
    print('False')

Please help me overcome this error

Thanks

3
  • the same way as to regular file, I guess: f = open(TEMPDIR, 'w'); f.write(something) Commented Mar 27, 2016 at 12:04
  • 1
    Did you search your error and try the several solutions that come up based on that message you are receiving? Commented Mar 27, 2016 at 12:05
  • Did you try these solutions ? Commented Mar 27, 2016 at 12:06

3 Answers 3

10

The default mode of TemporaryFile is "w+b", e.g. binary. You have to provide the mode explicitly for text:

TEMPDIR = tempfile.TemporaryFile(mode="w+")
Sign up to request clarification or add additional context in comments.

Comments

1

The default mode used to open the file returned by TempFile is 'w+b'. The b in that string means it's opened in binary mode, and you need to pass bytes instances to its write method, rather than str instances like you're doing.

You have a few options. You could encode your string to bytes. Or alternatively, you could pass a mode to TempFile to have it open the file in text mode (so that write expects Unicode str instances). Using a proper mode is probably the better solution, but your mileage may vary.

Comments

0

The docs explain that tempfile uses binary mode by default when opening a file to write to. Therefore, you can't write strings to it (this only works in text mode), only bytes objects.

So either override that default (as in Daniel's answer), or encode your strings with the appropriate encoding:

TEMPDIR.write("foo".encode("utf-8"))

or use a bytes object right away:

TEMPDIR.write(b"""B5IB6-ELAZ1-RAPY9-V8X1I-3...")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.