The error "TypeError: write() argument must be str, not bytes" occurs when we try to write bytes to a file which is not opened in the binary mode.

error

Problem

The following code with throw the above error:

with open('sample.txt', 'w') as my_file:
    my_file.write(b'Welcome to sharooq.com')
error code

Here, we are opening the file sample.txt text mode by passing the "w" as the second parameter. In order to write bytes to a file, we need to open the file in binary mode, which can be done by passing "wb" as the second parameter.

Solution

Let's rewrite the above code with the correct mode to resolve the issue.

with open('sample.txt', 'wb') as my_file:
    my_file.write(b'Welcome to sharooq.com')
correct code

Run the above code to update the sample.txt with the given input.

Welcome to sharooq.com
sample.txt

When using binary mode to open a file, we are writing and reading data as 'bytes' objects.

Transforming data with encoding and decoding

1, Writing a string to the output file

With binary mode, we cannot use the encoding keyword argument when opening a file. However, when writing into a file, we can decode the bytes as shown below.

with open('sample.txt', 'w', encoding='utf-8' ) as my_file:
  my_file.write(b'Welcome to sharooq.com'.decode('utf-8'))
code with encoding and decoding.

In the above example, we opened the file with text mode 'w' and specified the encodingkeyword as "utf-8".  Then, in order to write strings to the output file, we first wrote our data in binary and used the bytes.decode method to decode the written bytes into a string.

2, Writing bytes objects to the output file

Conversely, we can do the opposite of the above example. That is, we can open a file in binary mode and save it as bytes object onto the file using the str.encode method.

with open('sample.txt', 'wb') as my_file:
  my_file.write('Welcome to sharooq.com'.encode('utf-8'))

As shown in the above examples, you can use multiple techniques to interchange the data as needed for your requirement. If you found this article useful, feel free to check out some of the featured articles in my blog.