Solving Python Error – source code string cannot contain null bytes

Solving Python Error – source code string cannot contain null bytes is an error which happens in Python when you are working with a corrupt file.

In this article I am going to explain why the error is occurring and how to solve it using multiple solutions which may work for your particular case.

Explaining Python Error – source code string cannot contain null bytes

First of all, we need to understand why the error happens at all, the error usually happens because you accidentally messed up the file or if the creation of the file made it a corrupt file from the start.

The important line of the error message will look like something like this.

                                                                       #
source code string cannot contain null bytes
                                                                       #

To solve the problem above, I have a few solutions which have worked for me, bellow is a detailed explanation of the solutions.

Solution 1 : edit the file manually

A very simple solution is to edit the file manually. The error is usually caused by a null byte in the file.

You can use Notepad or another text editor to remove the null byte, clean the file and then save it.

Another similar fix, is to delete the file and then create it again.

If this error has fixed your problem then great. If it did not then try the solution bellow.

Solution 2 : a simple command

This solution is simple, you can clean your file by running the command bellow.

                                                                       #
sed -i 's/\x0//g' file.py
                                                                       #

While file.py is the faulty file which you are trying to clean.

If this did not fix your issue, try the solution bellow.

Solution 3 : another powerful command

Another solution is to run one command in order to remove the null byte.

Run the following command.

                                                                       #
python -c 'import sys; sys.stdout.write(sys.stdin.read().replace("\0", ""))' < file.py > file_new.py
                                                                       #

file.py is the faulty file which you are trying to edit and file_new.py is the new cleaned file.

The solutions above should be enough to solve the problem, if you like our effort make sure to consider donating to our Kofi account, there is a red button that you can use if you are feeling generous.

Summing-up

This is the end of this article guys, I hope one of these solutions worked for you depending on which OS you have, I wish you good luck with your Python Journey.

For donations you can use the red Kofi button above, keep learning and keep coding, cheers. If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/