TypeError: a bytes-like object is required, not 'str' when writing to a file in Python 3

This error occurs when you are trying to write a string to a file using the write() method in Python 3, but the file is opened in binary mode (using the 'b' flag when opening the file). To fix this, you need to encode the string to bytes before writing it to the file.

# Example code that causes the error
f = open('file.txt', 'wb')
string = 'hello'
f.write(string)
f.close()

Watch a course Python - The Practical Guide

To fix the error, you can use the encode() method to convert the string to bytes before writing it to the file:

# Corrected code
f = open('file.txt', 'wb')
string = 'hello'
f.write(string.encode())
f.close()

Alternatively, you can open the file in text mode using the 'w' flag instead of binary mode using the 'wb' flag.

f = open('file.txt', 'w')
string = 'hello'
f.write(string)
f.close()

This way you don't have to use .encode() method