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')
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')
or encode after adding a new line:
outfile.write((hash_digest + '\n').encode('utf-8'))
source share