10
import hashlib

infile = open("P:\\r.mp3", 'r+b')
data = infile.readline()
hash = hashlib.md5()
hash.update(data)

hash_digest = hash.hexdigest()
print(hash_digest)
#hash_digest = hash_digest.encode('utf-8')
print(hash_digest)
with open("lt.txt", 'ab') as outfile:
    outfile.write(hash_digest + '\n')   #error here

with open("syncDB.txt", 'rb') as fg:
    for data in fg:
    print(data)
outfile.write(hash_digest + '\n')
TypeError: 'str' does not support the buffer interface

How do I correct that and what do I need to learn to see me through these situations?

Also if I encode this in utf-8(uncomment) it gives out the following error:

TypeError: can't concat bytes to str
0

2 Answers 2

23

You're using Python 3, where there is a strict division between text (str) and data (bytes). Text can't be written to a file if you don't explicitly encode it first.

There are two ways to do this:

1) Open the file in text mode (possibly with an encoding specified) so that strings are automatically encoded for you:

with open("lt.txt", 'at', encoding='utf8') as outfile:
    outfile.write(hash_digest + '\n') # or print(hash_digest, file=outfile)

If you don't specify the encoding yourself when opening the file in text mode, the default encoding of your system locale would be used.

2) Encode the strings manually like you tried. But don't try to mix str with bytes like you did, either use a byte literal:

hash_digest = hash_digest.encode('utf-8')
with open("lt.txt", 'ab') as outfile:
    outfile.write(hash_digest + b'\n')   # note the b for bytes

or encode after adding the newline:

    outfile.write((hash_digest + '\n').encode('utf-8'))
Sign up to request clarification or add additional context in comments.

2 Comments

You don't need to call f.close() if you're using with-open-as. (Of course I realize you were simply matching the OP's code.)
Thanks ! I had problem with csv.writer , writer.writerow with same error. I've encountered problems adter switching from sys.stdout to file open(). Your solution solved my problems :).
-5

You must search in Google for 'str' does not support the buffer interface

You'll have plenty of answers like this one:

stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface

And for the second error **TypeError: can't concat bytes to str ** , I think you must write b'\n' in f.write(hex + '\n')

""" edit

yes Rosh Oxymoron is right, b'\n' , and not u'\n'

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.