In this article, we will discuss on how to fix the error message typeerror write argument must be str not bytes.
The typeerror: write argument must be str not bytes error typically occurs if you are trying to write bytes to a file without opening the file in wb mode.
Why we get TypeError: write() argument must be str, not bytes?
We get TypeError: write() argument must be str, not bytes because when we try to write binary data to a text file or a stream that expects a string.
Here an example on how the error occur:
with open('file.txt', 'w') as file:
file.write(b'hello')
Output:
Traceback (most recent call last):
File “C:\Users\Dell\PycharmProjects\pythonProject\main.py”, line 2, in
file.write(b’hello’)
TypeError: write() argument must be str, not bytes
The example code is causing an error because it is trying to write a byte string (b’hello’) to a text file opened in write mode (‘w’).
When a file is opened in write mode, it expects to receive a string as input, not bytes.
Also, read the other related articles about argument:
typeerror ‘encoding’ is an invalid keyword argument for this function
How to fix this error write argument must be str not bytes?
Here are the following solutions to fix this error write argument must be str not bytes.
Solution 1: Open the file in binary mode (‘wb’) instead of text mode
To solve the error write argument must be str not bytes, we need to open the file in binary mode (‘wb’) instead of text mode.
For example:
with open('file.txt', 'wb') as file:
file.write(b'hello')Solution 2: Encode the byte string as a string before writing it to the file
Another solution to solve the error is to encode the byte string as a string before writing it to the file.
For example:
with open('file.txt', 'w') as file:
file.write(b'hello'.decode('utf-8'))
The ‘b’ before the string ‘hello’ shows that it is a bytes object, which is decoded using the ‘utf-8’ encoding to convert it into a string before writing it to the file.
Solution 3: Using the rb (read binary) mode
The other way to solve the error is using the rb (read binary) mode.
For example:
with open('file.txt', 'rb') as file:
lines = file.readlines()
print(lines)
first_value = lines[0].decode('utf-8')It will reads all the lines in the file using the readlines() method and stores them in the lines variable.
Understanding argument-count TypeErrors
Every function call must match the function’s signature — required positionals, defaults, *args, **kwargs. Missing an argument, adding an extra, or using a wrong keyword all raise TypeError.
Common triggers
- Missing required positional.
compute()when signature iscompute(x, y). - Method called without self.
MyClass.method(arg)when it should beinstance.method(arg). - Keyword argument that doesn’t exist. Typo:
open(filepath, mode="r", encodig="utf-8")— encoding is misspelled. - Extra positional. Passing 3 args to a function that accepts 2.
- Mixing positional and keyword.
f(1, x=2)when x is the first parameter (double-assignment error).
Diagnostic pattern
# BAD
def send_email(to, subject, body, cc=None):
...
send_email("[email protected]", "hi", body_text="Hello")
# TypeError: send_email() missing 1 required positional argument: 'body'
# (because "hi" bound to subject and body_text is unknown)
# GOOD — align keyword args with actual parameters
send_email("[email protected]", "hi", body="Hello")
# or all keyword
send_email(to="[email protected]", subject="hi", body="Hello")
Best practices
- Use type hints. IDEs and type-checkers flag argument mismatches before you run.
- Use keyword-only arguments for optional parameters:
def send(*, to, subject, body)forces keyword syntax. - Read the docstring. Nested libraries sometimes rename kwargs across versions — check the docs.
Official documentation
Frequently Asked Questions
What is Python TypeError and what causes it?
TypeError is raised when an operation is applied to an object of the wrong type. Common patterns: calling a non-callable object, adding incompatible types (str + int), passing the wrong number of arguments, or accessing attributes on a NoneType. Each TypeError message names the operation and expected vs actual types, the fix is almost always to convert types explicitly (int(), str()) or fix the wrong variable assignment.
How do I quickly debug a Python TypeError?
Three steps: (1) Read the full error message, it names the exact operation and types involved. (2) Print the type of every variable in that line: print(type(var1), type(var2)). (3) Check what the function expected vs what you passed. Most TypeError fixes are 1-line type casts or fixing a variable that became None unexpectedly.
Should I catch TypeError or let it propagate?
For internal code, let TypeError propagate, it’s almost always a real bug (wrong type passed). For boundary code (parsing user input, third-party API responses), catch TypeError + ValueError together: try: parsed = int(value) except (TypeError, ValueError): parsed = 0. Catching internal TypeErrors hides bugs.
How do I prevent TypeError in production?
Three patterns: (1) Use type hints (def add(a: int, b: int) -> int) and check with mypy / pyright in CI. (2) Validate inputs at boundaries (Pydantic for FastAPI, DRF serializers for Django). (3) Default values that match expected types (return 0 not None for numeric functions). Static typing catches 80% of TypeErrors before runtime.
Where can I find more TypeError fixes?
Browse the TypeError reference hub for 220+ specific TypeError fixes. For broader Python debugging, see the Python Tutorial hub. For related error types, see ValueError and AttributeError guides.
Conclusion
In conclusion, by following the solutions in this article it will be able to help you to resolved the typeerror: write argument must be str not bytes .
FAQs
A bytes object is a sequence of bytes that represents binary data. Each byte is represented as an integer value between 0 and 255.
You can specify the mode when you open a file in Python using the “mode” parameter. For example, to open a file in binary mode, you would use the “wb” flag.
