2

The lines below give the error: TypeError: 'str' does not support the buffer interface. I have searched a lot. This is an issue in Python 3.

with codecs.open(filename, 'w', 'utf-8') as o:
    text = "I charge it at night & morning."
    txtEncode = text.encode('utf8')
    data = txtEncode.replace("&", "&")
    o.write(data)

Kindly suggest.

1 Answer 1

1

The codec will do all necessary encoding work when saving data to the file. Thus you can forget about the encoding details and do your work conveniently on strings.

This means: don't do this:

txtEncode = text.encode('utf8')

because type of txtEncode is bytes.

Here is the corrected code:

with codecs.open(filename, 'w', 'utf-8') as o:
    text = "I charge it at night & morning."
    data = text.replace("&", "&")
    o.write(data)

For a simple case like yours, open may be used instead of codecs.open. From the Python3 docs:

While the builtin open() and the associated io module are the recommended approach for working with encoded text files, this module [i.e. codecs] provides additional utility functions and classes that allow the use of a wider range of codecs when working with binary files

Sign up to request clarification or add additional context in comments.

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.