TypeError: 'str' does not support the buffer interface

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 fix this and what do I need to learn to see me in these situations?

Also, if I code this in utf-8 (uncomment), it throws the following error:

 TypeError: can't concat bytes to str 
+6
source share
2 answers

You are using Python 3, where there is a strict separation of text ( str ) and data ( bytes ). Text cannot be written to a file unless you explicitly code it.

There are two ways to do this:

1) Open the file in text mode (possibly with the specified encoding) so that the lines 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 do not specify the encoding yourself when opening the file in text mode, the default encoding for your system will be used.

2) Encode the strings manually as you tried. But don't try to mix str with bytes like you, or 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 a new line:

  outfile.write((hash_digest + '\n').encode('utf-8')) 
+17
source

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

You will have many answers like this:

fooobar.com/questions/18775 / ...

And for the second error ** TypeError: cannot concatenate bytes to str **, I think you should write b'\n' in f.write(hex + '\n')

"" edit

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

-3
source

Source: https://habr.com/ru/post/895534/


All Articles