Categories
Python Answers

How to fix TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python 3?

Spread the love

Sometimes, we want to fix TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python 3.

In this article, we’ll look at how to fix TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python 3.

How to fix TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python 3?

To fix TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python 3, we can open the file with open and 'r‘.

For instance, we write

with open(fname, 'r') as f:

  # ...

to open the file at path fname with open.

We open it with read permission as a string with 'r'.

Conclusion

To fix TypeError: a bytes-like object is required, not ‘str’ when writing to a file in Python 3, we can open the file with open and 'r‘.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *