TypeError: write() argument must be str, not X in Python

avatar

Last updated: Jan 29, 2023 Reading time · 11 min

banner

# Table of Contents

  • TypeError: write() argument must be str, not BYTES
  • TypeError: write() argument must be str, not LIST
  • TypeError: write() argument must be str, not DICT
  • TypeError: write() argument must be str, not TUPLE
  • TypeError: write() argument must be str, not NONE

# TypeError: write() argument must be str, not bytes

The Python "TypeError: write() argument must be str, not bytes" occurs when we try to write bytes to a file without opening the file in wb mode.

To solve the error, open the file in wb mode to write bytes or decode the bytes object into a string.

typeerror write argument must be str not bytes

Here is an example of how the error occurs.

We opened the file in w mode and tried writing bytes to it which caused the error.

The string literal in the example is prefixed with b , so it is a bytes object.

# Open the file in wb (write binary) mode to write bytes

If you need to write bytes to a file, open it in wb (write binary) mode rather than w (write text) mode.

writing bytes to a file

We opened the file in wb (binary) mode to write bytes to it.

Note that you shouldn't specify the encoding keyword argument when you open a file in binary mode.

If you need to also read from the file, use the rb (read binary) mode.

read from file using rb mode

The readlines() method returns a list of bytes objects, so we used the decode() method to convert the first item in the list to a string.

You can use a list comprehension to convert all lines in the file to strings.

using list comprehension to convert all lines to strings

List comprehensions are used to perform some operation for every element or select a subset of elements that meet a condition.

# Open the file in w (write text) mode to write text

Alternatively, you can decode the bytes object into a string.

open file in write text mode

Notice that we used the bytes.decode( method to decode the bytes object into a string.

We opened the JSON file in w (write text) mode.

When a file is opened in text mode, we read and write strings from and to the file.

If you need to read from the file, open it in r (read text) mode.

Those strings are encoded using a specific encoding (utf-8 in the example).

If you want to both read from and write to the file, use the r+ mode when opening it.

Note that you cannot specify encoding when opening a file in binary mode.

When a file is opened in binary mode, data is read and written as bytes objects.

The bytes.decode method returns a string decoded from the given bytes. The default encoding is utf-8 .

You can decode your bytes object to a string if you want to write strings to the file.

Conversely, the str.encode method returns an encoded version of the string as a bytes object. The default encoding is utf-8 .

The example shows how to encode a string to a bytes object and write the bytes to a file.

# TypeError: write() argument must be str, not list

The Python "TypeError: write() argument must be str, not list" occurs when we try to write a list object to a file using the write() method.

To solve the error, use the join() method to join the list into a string.

typeerror write argument must be str not list

# Use the str.join() method to join the list into a string

One way to solve the error is to use the str.join() method to join the list into a string.

We used a comma as the separator between the items of the list, but you can use any other separator.

You can also use an empty string if you don't need a separator between the elements.

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

# All values in the collection must be strings

If your list contains numbers or other types, convert all of the values to string before calling join() .

The string the method is called on is used as the separator between elements.

If you don't need a separator and just want to join the iterable's elements into a string, call the join() method on an empty string.

# Converting a list to a string before writing it to the file

Alternatively, you can pass the list to the str() class to convert it to a string before writing it to the file.

The str() class converts the supplied value to a string and returns the result.

You can also convert the list to a JSON string before writing it to the file.

The json.dumps method converts a Python object to a JSON formatted string.

# TypeError: write() argument must be str, not dict

The Python "TypeError: write() argument must be str, not dict" occurs when we pass a dictionary to the write() method.

To solve the error, convert the dictionary to a string or access a specific key in the dictionary that has a string value.

typeerror write argument must be str not dict

# Convert the dictionary to a string before writing it to the file

One way to solve the error is to convert the dictionary to a string.

The str() class converts the given value to a string and returns the result.

You can also convert the dictionary to a JSON string by using the json.dumps method.

# Writing a specific dictionary value to the file

If you meant to access a specific key in the dictionary, use square brackets.

# Checking what type a variable stores

If you aren't sure what type a variable stores, use the built-in type() class.

The type class returns the type of an object.

The isinstance function returns True if the passed-in object is an instance or a subclass of the passed in class.

# TypeError: write() argument must be str, not tuple

The Python "TypeError: write() argument must be str, not tuple" occurs when we try to write a tuple object to a file using the write() method.

To solve the error, use the join() method to join the tuple into a string, e.g. my_file.write(','.join(my_tuple)) .

typeerror write argument must be str not tuple

# Join the tuple's elements into a string before writing to the file

One way to solve the error is to use the str.join() method to join the tuple into a string.

We used a comma as the separator between the items of the tuple, but you can use any other separator or an empty string if you don't need a separator between the elements.

# Convert all values in the tuple to strings

If your tuple contains numbers or other types, convert all of the values to string before calling join() .

# Converting the tuple to a string or a JSON string

Alternatively, you can pass the tuple to the str() class to convert it to a string before writing it to the file.

You can also convert the tuple to a JSON string before writing it to the file.

Since JSON doesn't support tuples, the tuple gets converted to a list.

# How tuples are constructedin Python

In case you declared a tuple by mistake, tuples are constructed in multiple ways:

  • Using a pair of parentheses () creates an empty tuple
  • Using a trailing comma - a, or (a,)
  • Separating items with commas - a, b or (a, b)
  • Using the tuple() constructor

If you aren't sure what type of object a variable stores, use the type() class.

# TypeError: write() argument must be str, not None

The Python "TypeError: write() argument must be str, not None" occurs when we pass a None value to the write() method.

To solve the error, correct the assignment and pass a string to the write() method.

typeerror write argument must be str not none

We passed a None value to the write method which caused the error.

The method takes a string and writes it to the file.

# Common sources of None values in Python

The most common sources of None values are:

  • Having a function that doesn't return anything (returns None implicitly).
  • Explicitly setting a variable to None .
  • Assigning a variable to the result of calling a built-in function that doesn't return anything.
  • Having a function that only returns a value if a certain condition is met.

# A function that doesn't return a value returns None

Functions that don't explicitly return a value return None .

You can use a return statement to return a value from a function.

# Checking if the variable is not None before writing to the file

Use an if statement if you need to check whether a variable doesn't store a None value before writing it to the file.

Alternatively, you can provide an empty string as a fallback.

# Having a function that returns a value only if a condition is met

Another common cause of the error is having a function that returns a value only if a condition is met.

The if statement in the get_string function is only run if the passed in string has a length greater than 3 .

To solve the error in this scenario, you either have to check if the function didn't return None or return a default value if the condition is not met.

Now the function is guaranteed to return a string regardless if the condition is met.

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

Python TypeError: write() argument must be str, not bytes

Understanding the error.

Encountering a TypeError: write() argument must be str, not bytes in Python can be a frustrating experience. This often occurs when dealing with file operations, especially when you’re trying to write binary data to a file opened in text mode instead of binary mode. Understanding the root of the problem and knowing how to fix it can save you precious debugging time.

What is the Point?

The key to resolving this error lies in understanding the differences between strings and bytes in Python. Strings are sequences of characters, whereas bytes are sequences of bytes. Python 3 made a clear distinction between these two, which is why attempting to write bytes to a file opened in text mode causes a TypeError.

Solution 1: Converting Bytes to String

If your data can be safely converted to a string format using character encoding, this is often the simplest solution.

  • Encode your bytes object using a character encoding scheme (usually utf-8 ).
  • Write the encoded string to the file.

Code Example:

Notes: While this solution is simple and effective for data that can be converted, it’s not suitable for binary data not meant to be read as text (e.g., images, executable files).

Solution 2: Opening File in Binary Mode

This solution involves opening the file in a mode that accepts bytes directly, avoiding the need for conversion.

  • Open the file in binary mode by using ‘wb’ instead of ‘w’.
  • Write bytes directly to the file.

Notes: This is the preferable solution for writing binary data. However, if you’re not dealing with binary data, make sure that your data doesn’t need to be in a string format for readability or processing reasons.

Solution 3: Using Buffering with io.BytesIO

For complex scenarios where you need to first manipulate the bytes in memory before writing them, using a buffer can be handy.

  • Import io module.
  • Create a buffer using io.BytesIO() .
  • Write the bytes to the buffer.
  • Write the buffer’s contents to a file in binary mode.

Notes: This solution is especially useful when working with binary data that needs to manipulated or generated in memory before being persisted to disk. It’s a bit more complex but offers greater flexibility.

Fixing the TypeError: write() argument must be str, not bytes involves understanding the nature of your data and how you intend to use it. Whether it’s converting your bytes to a string, writing in binary mode, or using a buffer, the right solution depends on your specific case. By understanding these techniques, you can avoid common pitfalls and work more efficiently with file I/O in Python.

Next Article: Fixing Python ValueError: Circular Reference Detected

Previous Article: Python TypeError: object of type ‘NoneType’ has no len()

Series: Common Errors in Python and How to Fix Them

Related Articles

  • Python Warning: Secure coding is not enabled for restorable state
  • 4 ways to install Python modules on Windows without admin rights
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)

Search tutorials, examples, and resources

  • PHP programming
  • Symfony & Doctrine
  • Laravel & Eloquent
  • Tailwind CSS
  • Sequelize.js
  • Mongoose.js

How to Fix the TypeError: must be str, not int in Python

  • Python How-To's
  • How to Fix the TypeError: must be str, …

How to Fix the TypeError: must be str, not int in Python

String concatenation refers to combining multiple strings into a single string. In Python, we can use the + symbol between variables referring to strings or raw strings themselves to join them together. Or, we can put all the strings that we wish to join inside a list and use the built-in join() method Python to merge them into one.

While using both the methods above, if we are not careful with the data types of the variables and the raw values, we can run into the TypeError exception. This article will talk about how to fix this issue in Python.

Fix the TypeError: must be str, not int in Python

We will discuss a couple of ways that we can use to fix this error in Python.

the Obvious Approach

The first solution is an obvious one; be alert about the variables and the raw values you are using. Try not to concatenate a string with an integer, class object, or boolean value.

the str() Method in Python

The second solution is to use the built-in str() method in Python. This method returns a string version of the passed object, for example, an integer, a floating-point value, a boolean, a class object, a list, etc. For class objects, this method returns the result of the __repr__() method or the __str__() method. Refer to the following Python code to understand this str() function practically.

Now, let us see how to use this function for string concatenation. Refer to the following code for the same.

The str() function will convert all the values into their respective string values. And, further, we can safely concatenate the strings together without running into any exceptions.

Formatted Strings in Python

The third way is to use formatted strings. Formatted strings refer to strings prefixed with an f . These strings allow us to insert variables or logic inside regular strings. The formulated or the final string would have the string representations of the values stored by the variables and the values returned by the logic or function calls. The logic and the variables are inserted inside {} present inside the strings.

Refer to the following Python code for the discussed approach.

Note the presence of an f at the beginning of the string and multiple {} inside the string.

Vaibhav Vaibhav avatar

Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.

Related Article - Python Error

  • Can Only Concatenate List (Not Int) to List in Python
  • How to Fix Value Error Need More Than One Value to Unpack in Python
  • How to Fix ValueError Arrays Must All Be the Same Length in Python
  • Invalid Syntax in Python
  • How to Fix the TypeError: Object of Type 'Int64' Is Not JSON Serializable
  • How to Fix the TypeError: 'float' Object Cannot Be Interpreted as an Integer in Python

Solved - "TypeError: write() argument must be str, not dict" in Python

The error occurs when you pass a dictionary to the write() method in Python. You can solve the error by converting the dictionary to a string or fixing some other potential mistakes as explained in this article.

Sharooq Salaudeen

Sharooq Salaudeen

Read more posts by this author .

The error "TypeError: write() argument must be str, not dict" occurs when you pass a dictionary to the write() method in Python. The error might occur when you accidentally passed the whole dictionary instead of a specific key in the dictionary to the write() method. Or if you intended to pass the dictionary itself, you need to convert the dictionary to a string.

write() argument must be str

Here is an example of the code in which the error occurs:

Here we passed the "dict" object directly to the write() method. This will result in the error mentioned above.

1, Convert the dictionary to a string

You can use the str() method to convert the dictionary object into a string and pass it to the write() method as shown in the following code.

The output file is as follows:

2, Convert the dictionary to a JSON string using json.dumps()

You can convert the dictionary to a JSON string using json.dumps() method. The following code demonstrates the same:

The output file will be in a JSON formatted string as follows:

3, Accessing a specific key in the dictionary

If you meant to output a specific value to a key in the dictionary, you can follow the following code:

The output will be as following:

The value of the key we are accessing in the dictionary needs to be a string. The write() method only accepts a string as its argument.

How to check the type of a value in the dictionary?

You can use the built-in type() or isinstace() method to check the type of a value.

write() argument must be str

The type() method returns the type of a given object.

The isinstance() method takes two arguments. First, the actual value and the second, a type. If the value matches the type, it will return "True".

I hope this was helpful to you. You can visit the feature articles section to find interesting topics. See you in the next one.

Subscribe to Sharooq

Join the growing community of friendly readers through my monthly newsletter.

Sharooq

Stay up to date! Join my monthly newsletter and get the latest productivity tips, engineering advancements and practical life advice directly to your inbox.

LearnShareIT

How To Solve TypeError: Write() Argument Must Be Str, Not List

TypeError: write() argument must be str, not list

“ TypeError: write() argument must be str, not list ” is a common error related to Python files when writing strings. The below explanations can help you know more about this error of causes and solutions.

Table of Contents

How does the TypeError: write() argument must be str, not list occur?

Basically, “argument must be str’” means that the parameter or the instance you are passing to the method does not have the type of string type (in Python it is called str). Mostly, the error will happen when you call this method on a file and with the list passed to its parameter in Python. For example:

Output in file new.txt

The reason behind the lack of the str argument is that you may have mistakes in assuming the arguments in the write method will automatically convert the argument into string type. In fact, the method write() will not convert anything into a string, it just raises the error whenever the parameter is not str. The method print() and write() are most well-known in Python, however, the print() will auto-convert the arguments into strings for you, but the write() does not.

How to solve this error ?

Using str().

Fortunately, Python has another method which can help you to convert a list into a string. You can read the syntax and usage of the str() method here . To use this method, just call it on your string variable, which is actually of type list rather than str:

The str() method produces a new string representing elements in the list separated by a comma. However, if you may want to replace commas with another character or remove separators, then you can read the next solution.

Another way to overcome this problem is to convert the list into a string with the commas replaced as another character by calling the method on the separator string you want:

Another example without creating a temporary separator variable:

We have learned how to solve the TypeError: write() argument must be str, not list. By finding out the reasons and replacing the list with a string rather than a list with the help of third methods, you can easily avoid this error. Good luck to you!

Maybe you are interested :

  • TypeError: object of type ‘float’ has no len() in Python
  • TypeError: ‘str’ object cannot be interpreted as an integer
  • TypeError: unhashable type: ‘ set’ in Python

write() argument must be str

I’m Edward Anderson. My current job is as a programmer. I’m majoring in information technology and 5 years of programming expertise. Python, C, C++, Javascript, Java, HTML, CSS, and R are my strong suits. Let me know if you have any questions about these programming languages.

Name of the university: HCMUT Major : CS Programming Languages : Python, C, C++, Javascript, Java, HTML, CSS, R

Related Posts

List.append() not working in python.

  • Thomas Valen
  • January 18, 2023

The list.append() function is used to add an element to the current list. Sometimes, list.append() […]

How To Print A List In Tabular Format In Python

To print a list in Tabular format in Python, you can use the format(), PrettyTable.add_rows(), […]

write() argument must be str

How To Solve The Error: “ModuleNotFoundError: No module named ‘google.protobuf'” in Python

The Error: “ModuleNotFoundError: No module named ‘google.protobuf’” in Python occurs because you have not installed […]

Leave a Reply Cancel reply

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

Save my name, email, and website in this browser for the next time I comment.

How to fix TypeError: must be str, not int in Python

by Nathan Sebhastian

Posted on Mar 21, 2023

Reading time: 1 minute

write() argument must be str

One error that you might encounter when working with Python is:

This error occurs when you specify an integer in the place where Python expects a string.

This tutorial will show you examples that cause this error and how to fix it.

How to reproduce this error

Suppose you have an integer variable that stores today’s temperature as follows:

Next, you try to print a sentence that includes the temperature value as follows:

Python doesn’t allow you to concatenate a string together with an integer.

How to fix this error

To resolve this error, you can convert any integer value in your print statement into a string using the str() function.

Run the code again and notice that you didn’t receive any error this time.

I hope this tutorial is helpful. Happy coding! 👋

Take your skills to the next level ⚡️

I'm sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I'll send new stuff straight into your inbox!

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials. Learn statistics, JavaScript and other programming languages using clear examples written for people.

Learn more about this website

Connect with me on Twitter

Or LinkedIn

Type the keyword below and hit enter

Click to see all tutorials tagged with:

Search code, repositories, users, issues, pull requests...

Provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cannot savefig to stdout: TypeError: write() argument must be str, not bytes #18049

@iljah

iljah commented Jul 24, 2020

Sorry, something went wrong.

@QuLogic

QuLogic commented Jul 24, 2020

@QuLogic

iljah commented Jul 25, 2020

@timhoffm

No branches or pull requests

@QuLogic

How to Fix TypeError: write() argument must be str, not None When Parsing JSON Data in Python 3.x

Abstract: Learn how to fix the TypeError: write() argument must be str, not None error when trying to parse JSON data from one file to another in Python 3.x. This article will cover the common causes of the error and provide step-by-step solutions to resolve it.

If you are working with JSON data in Python 3.x, you may encounter the following error:

This error occurs when you try to write JSON data to a file or a network socket using the write() method, but the data you are trying to write is None .

In this article, we will discuss how to fix this error when working with JSON data in Python 3.x.

Understanding the Error

Before we dive into the solution, let's take a closer look at the error message:

The error message tells us that the write() method expects a string as an argument, but it received None instead. This means that the variable you are trying to write is None , which is not a string.

Let's take a look at an example:

In this example, we are trying to write JSON data to a file using the json.dump() method. However, we are passing f.write() as an argument to the method, which is causing the error.

The f.write() method returns None , which is not a string. Therefore, we need to pass a string as an argument to the json.dump() method.

Fixing the Error

To fix the error, we need to pass a string as an argument to the json.dump() method. We can achieve this by calling the json.dumps() method, which converts a Python object into a JSON string.

Let's take a look at the updated example:

In this example, we are calling the json.dumps() method to convert the data object into a JSON string. We are then passing the JSON string as an argument to the f.write() method.

This will fix the error and allow us to write JSON data to a file or a network socket.

If you encounter the TypeError: write() argument must be str, not None error when working with JSON data in Python 3.x, it means that you are trying to write None to a file or a network socket. To fix the error, you need to pass a string as an argument to the json.dump() method by calling the json.dumps() method to convert the Python object into a JSON string.

Tags: :  Python 3.x JSON file parsing TypeError

Latest news

  • BlazorWASM Unable to Load Static HTML Page in wwwroot Folder: A Solution
  • Handling Errors Differently: Interactive vs Non-Interactive Modes in Subprocess Bash and Python Script
  • Error in Next.js Application: Supabase from() Not a Function
  • Changing Background Color of el-tooltip
  • NPMINSTALL GRPC: Docker Failed - Self-Signed Certificate (Certificate Chain) in gRPC nestJS Project
  • Understanding Missing Definition with Koin Annotations in SharedPreferenceModule
  • Error in Running Java Project with EXE using Launch4j
  • Extracting SSL Encryption Protocol Types Using Alamofire
  • C++ Code Not Reading File Correctly: ifstream with Grades.txt
  • Modal No Content Load Issue in Homepage Website
  • RuntimeError with tf.data.Dataset in TensorFlow: Python-style iteration eager mode in tf.function
  • Unable to Click 'Accept continue' in Google Pop-up using Selenium WebDriver C#
  • Fixing Overexposed Colors in Exported Final Cut Pro iPad Videos
  • Resolving CORS Issue in Spring Boot Project Connected to ReactJS Frontend
  • 15% Higher Plotchar Value Function with RMA_nn_High
  • Troubleshooting WordPress: New Theme Installation keeps showing 'Block New Theme Installed' message
  • Laravel App Not Connected to MySQL Database: A Solution
  • Customizing Makebox: Title, Image, and CSS for a Specific Height
  • Javascript Import & Export: Breaking Code with Multiple Files
  • Edit Function Failing to Save New Text: Date Values Not Replacing Old Ones
  • Making the 'Scroll Left Page' Button Stick: A Menu Bar Solution
  • Resolving Undefined References When Compiling Apache Server on Raspberry Pi
  • CSS Styling for Scrollable Content: A Chat History Example
  • Using EditModal Properly in PHP: A Database Example with mhs.php
  • Properly Mocking update One Method in Nest.js using Jest
  • Managing Multiple Entries with Aliases in NuShell: A Bash Approach
  • Interpolating Annual Data Monthly: A Common Challenge
  • Dragging View Angle Makes ScrollView Break Drag Gesture: Horizontal vs Vertical
  • PHPStorm CSS Completion Stopped Working in Laravel Projects: A Solution
  • Understanding GraphQL Resolver Return Objects
  • Solving Equations with Higher Powers: Finding the Value of 'k'
  • Suppressing Checkmarks in UITableView Left-Editing Mode
  • Displaying PDF Files from Backend Server using react-pdf-viewer in React.js
  • Aggregating Repeated Elements and Adding a Quantity Field with Django QuerySet
  • Angular App: Triggering GET Requests via REST API Manual

Improvements to static analysis in the GCC 14 compiler

Featured image for: Value range propagation in GCC with Project Ranger.

I work at Red Hat on GCC, the GNU Compiler Collection . For the last five releases of GCC, I've been working on -fanalyzer , a static analysis pass that tries to identify various problems at compile-time, rather than at runtime. It performs "symbolic execution" of C source code—effectively simulating the behavior of the code along the various possible paths of execution through it.

This article summarizes what's new with -fanalyzer in GCC 14 , which I hope will be officially released sometime in April 2024.

Solving the halting problem?

Obviously I'm kidding with the title here, but for GCC 14 I've implemented a new warning: -Wanalyzer-infinite-loop  that's able to detect some simple cases of infinite loops.

For example, consider the following C code:

If you look closely, you'll see that the user probably made the second for statement by copying the first one, but forgot to change the increment clause from an i to a j .

GCC 14's -fanalyzer  option successfully detects this, with this output:

The output could be more readable here—you have to read the events in order of their numbers, from (1) to (5) . For GCC 15 I hope to improve this, perhaps with ASCII art that highlights the path taken by control flow.

I find the Compiler Explorer website very useful for trying out code snippets with different compilers and options. You can try the above example on it here .

Visualizing buffer overflows

The analyzer gained support in GCC 13 for bounds checking with a -Wanalyzer-out-of-bounds  warning.

For example, given the out-of-bounds write in strcat in:

The analyzer emits this message:

I've been unhappy with the readability of these messages: it describes some aspects of the problem, but it's hard for the user to grasp exactly what the analyzer is "thinking."

So for GCC 14, I've added the ability for the analyzer to emit text-based diagrams visualizing the spatial relationships in a predicted buffer overflow. For the above example (which you can try here in Compiler Explorer ) it emits the diagram shown in Figure 1.

Screenshot of diagram showing buffer overflow

This diagram shows the destination buffer populated by the content from the strcpy call, and thus the existing terminating NUL byte used for the start of the strcat call.

For non-ASCII strings such as this:

It can show the UTF-8 representation of the characters (Figure 2).

FIXME

This demonstrates that the overflow happens partway through the メ character (U+30E1) . ( Link to Compiler Explorer ).

Analyzing C string operations

I've put some work into better tracking C string operations in GCC 14's analyzer.

One of the improvements is that the analyzer now simulates APIs that scan a buffer expecting a null terminator byte, and will complain about code paths where a pointer to a buffer that isn't properly terminated is passed to such an API.

I've added a new function attribute null_terminated_string_arg( PARAM_IDX )  for telling the analyzer (and human readers of the code) about parameters that are expected to be null-terminated strings. For example, given this buggy code:

Here, the analyzer correctly complains that str doesn't have a null terminator byte, and thus example_fn will presumably read past the end of the buffer:

Again, you can try this example in Compiler Explorer here .

Taint analysis

The analyzer has a form of "taint analysis", which tracks attacker-controlled inputs, places where they are sanitized, and places where they are used without sanitization. In previous GCC releases this was too buggy to enable by default, with lots of false positives, so I hid it behind an extra command-line argument. I've fixed many bugs with this, so for GCC 14 I've enabled this by default when -fanalyzer  is selected. This also enables these 6 taint-based warnings:

  • -Wanalyzer-tainted-allocation-size
  • -Wanalyzer-tainted-array-index
  • -Wanalyzer-tainted-assertion
  • -Wanalyzer-tainted-divisor
  • -Wanalyzer-tainted-offset
  • -Wanalyzer-tainted-size

For example, here's an excerpt from CVE-2011-2210 from the Linux kernel:

You can see a more full version at Compiler Explorer . In particular, I added __attribute__((tainted_args)) to the __SYSCALL_DEFINEx macro to indicate to the analyzer that the arguments to osf_getsysinfo are coming from across a trust boundary, and thus should be considered tainted.

With GCC 14, the analyzer is able to detect the vulnerability (again, edited somewhat for brevity):

The issue is that the attempt to sanitize nbytes was written as

when it should have been

With a fixed version of that conditional, the analyzer is silent .

I'm continuing to work on running the analyzer on the kernel to look for vulnerabilities (and fix false positives in the analyzer).

Try it out!

We're still fixing bugs, but we hope that GCC 14 will be ready to officially release (as 14.1) sometime in April 2024.

With my "downstream" hat on, we're already using the prerelease (GCC 14.0) within Fedora 40 Beta .

Finally, you can use the excellent Compiler Explorer site to play with the new compiler. Have fun!

  • Red Hat Enterprise Linux
  • Red Hat OpenShift
  • Red Hat Ansible Automation Platform
  • See all products
  • See all technologies
  • Developer Sandbox
  • Developer Tools
  • Interactive Tutorials
  • API Catalog
  • Operators Marketplace
  • Learning Resources
  • Cheat Sheets

Communicate

  • Contact sales
  • Find a partner

Report a website issue

  • Site Status Dashboard
  • Report a security problem

RED HAT DEVELOPER

Build here. Go anywhere.

We serve the builders. The problem solvers who create careers with code.

Join us if you’re a developer, software engineer, web designer, front-end designer, UX designer, computer scientist, architect, tester, product manager, project manager or team lead.

Red Hat legal and privacy links

  • About Red Hat
  • Contact Red Hat
  • Red Hat Blog
  • Diversity, equity, and inclusion
  • Cool Stuff Store
  • Red Hat Summit
  • Privacy statement
  • Terms of use
  • All policies and guidelines
  • Digital accessibility

IMAGES

  1. Typeerror: Write() Argument Must Be Str, Not Bytes Explained

    write() argument must be str

  2. [Solved] TypeError: write() argument must be str, not

    write() argument must be str

  3. TypeError: write() argument must be str, not list

    write() argument must be str

  4. How To Solve TypeError: Write() Argument Must Be Str, Not List

    write() argument must be str

  5. [SOLVED] Typeerror: write argument must be str not bytes

    write() argument must be str

  6. How To Write a Compelling Argumentative Essay: Expert Tips & Guide

    write() argument must be str

VIDEO

  1. Europe But Top Comments Change İt Part 3! Comment:@muratalimuratl3264

  2. 3.14.2024 Thursday 4:28 today's word is "_____ "

  3. 'We don't understand'

  4. Common Core Math

  5. What is an Argument synthesis? BA/BSW 3rd Year Compulsory English New Syllabus

  6. Receive God's Abundance

COMMENTS

  1. TypeError: write() argument must be str, not X in Python

    The Python "TypeError: write() argument must be str, not bytes" occurs when we try to write bytes to a file without opening the file in wb mode. To solve the error, open the file in wb mode to write bytes or decode the bytes object into a string.

  2. Python

    TypeError: write() argument must be str, not bytes. is: fw = open('./result.txt','wb') "b" for binary makes the difference. Share. Improve this answer. Follow edited Dec 4, 2019 at 12:39. Hrishi. 1,404 1 1 gold badge 13 13 silver badges 29 29 bronze badges. answered Dec 4, 2019 at 10:10.

  3. Fix Python TypeError: write() argument must be str, not bytes

    To conclude, the message TypeError: write() argument must be str, not bytes occurs in Python when you try to write bytes to a file object that's opened in w mode.. The w mode only accepts a string as input, so if you want to write bytes to the file, you need to open the file in wb mode.. Alternatively, you can also convert the bytes object to a string using the decode() method.

  4. Python TypeError: write() argument must be str, not bytes

    Conclusion. Fixing the TypeError: write() argument must be str, not bytes involves understanding the nature of your data and how you intend to use it. Whether it's converting your bytes to a string, writing in binary mode, or using a buffer, the right solution depends on your specific case. By understanding these techniques, you can avoid ...

  5. Difference between write and writelines in Python

    The write() method expects a string as an argument and writes it to the file. If we provide a list of strings, it will raise an exception. The writelines() method expects an iterable argument. Also, the write() method displays the output but does not provide a new line character, whereas the writelines() method displays the output and provides ...

  6. Solved

    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. 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 ...

  7. How to Fix the TypeError: must be str, not int in Python

    the str() Method in Python. The second solution is to use the built-in str() method in Python. This method returns a string version of the passed object, for example, an integer, a floating-point value, a boolean, a class object, a list, etc. For class objects, this method returns the result of the __repr__() method or the __str__() method.

  8. TypeError: write() argument must be str, not bytes (Python)

    This write-up will provide a detailed guide on resolving the "TypeError: write () argument must be str, not bytes" in Python. This guide will cover the following concepts: Reason: Opening File in "w" Mode for Writing Bytes. Solution 1: Open the File in "wb" Mode. Solution 2: Decoding the Byte Object into String.

  9. Solved

    type output. The type() method returns the type of a given object.. The isinstance() method takes two arguments. First, the actual value and the second, a type. If the value matches the type, it will return "True". I hope this was helpful to you.

  10. How To Solve TypeError: Write() Argument Must Be Str, Not List

    [' LEARNSHAREIT '] Traceback (most recent call last): File "main.py", line 8, in <module> file.write(string) TypeError: write() argument must be str, not list. The reason behind the lack of the str argument is that you may have mistakes in assuming the arguments in the write method will automatically convert the argument into string type.

  11. How to fix TypeError: must be str, not int in Python

    To resolve this error, you can convert any integer value in your print statement into a string using the str() function. Example 1: temp_f = 42 print ( "Today's temperature is: " + str ( temp_f ) + "F" )

  12. Typeerror: Write() Argument Must Be Str, Not Bytes Explained

    2. Why typeerror: write() argument must be str, not bytes Occurs in Pickle? The typeerror: write() argument must be str, not bytes pickle occurs because if the output needs to be opened in binary mode, the command should be given as f = open('varstor.txt','wb') and not f = open('varstor.txt','w'). If you run the wrong command ...

  13. Cannot savefig to stdout: TypeError: write() argument must be str, not

    Cannot savefig to stdout: TypeError: write() argument must be str, not bytes #18049. Closed iljah opened this issue Jul 24, 2020 · 4 comments Closed Cannot savefig to stdout: TypeError: write() argument must be str, not bytes #18049. iljah opened this issue Jul 24, 2020 · 4 comments Labels. Community support Users in need of help.

  14. python

    Python write() argument must be str. 252. Writing Unicode text to a text file? 342. Using pickle.dump - TypeError: must be str, not bytes. 80. Python 3 TypeError: must be str, not bytes with sys.stdout.write() 25. Download attachments from Gmail using Gmail API. 7. Save HTML Source Code to File. 2.

  15. How to Fix TypeError: write() argument must be str, not None When

    How to Fix TypeError: write() argument must be str, not None When Parsing JSON Data in Python 3.x

  16. TypeError: write() argument must be str, not list

    keyboard: TypeError: write() argument must be str, not listThanks for taking the time to learn more. In this video I'll go through your question, provide var...

  17. TypeError: write() argument must be str, not dict

    TypeError: write() argument must be str, not bytes (Python 3 vs Python 2 ) 0. write() argument must be str, not list. 2. Python: TypeError: write() takes exactly one argument (2 given) 1. TypeError: write() argument must be str, not int. 2. AttributeError: 'str' object has no attribute 'keys' when trying to use writerow. 0.

  18. CSV を出力しようとすると TypeError: write() argument must be str エラーが発生する

    差出名称,内部印字区分,外部仕分区分. 実行時のエラーメッセージ. Traceback (most recent call last): File "csv_convert.py", line 21, in <module>. outptfile.write(row) TypeError: write() argument must be str, not list. エラーがTypeErrorということで正しい型の書き方にしないといけないのは理解 ...

  19. Improvements to static analysis in the GCC 14 compiler

    So for GCC 14, I've added the ability for the analyzer to emit text-based diagrams visualizing the spatial relationships in a predicted buffer overflow. For the above example (which you can try here in Compiler Explorer) it emits the diagram shown in Figure 1. Figure 1: Visualizing buffer overflows in GCC 14.

  20. TypeError: write() argument must be str, not int

    Your code will overwrite the file each time (hence why you only get the last value). If you want to add to it you can try using mode="a" (which stands for append) which should write each value to the end of the file. You might also want to think about if you want to add a delimiter to separate the numbers. - Sven Harris.

  21. python

    I'm creating a dice game in Python 3.7.2. I need to write the results to a text file but with my current code I'm getting errors. I've tried just casting to a string but that just causes more issues.