老猿在导入一个Python模块时报错:

>>> import restartnet.py
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
import restartnet.py
ValueError: source code string cannot contain null bytes


使用IDLE去打开该模块对应文件时,会报:

Python使用import导入模块时报ValueError: source code string cannot contain null bytes的解决方案_打开文件

会发现是编码有问题,老猿使用缺省编码cp936去打开时还是报错:

Python使用import导入模块时报ValueError: source code string cannot contain null bytes的解决方案_打开文件_02

老猿知道这一定是文件的编码问题,想起来当时为了测试文件编码,将该文件存为了:UTF-16编码,在IDLE中打开文件时填入UTF-16:

Python使用import导入模块时报ValueError: source code string cannot contain null bytes的解决方案_编码问题_03

文件正常打开。如图:

Python使用import导入模块时报ValueError: source code string cannot contain null bytes的解决方案_编码问题_04

知道是该编码的问题后,就按​​《Python中import模块时报SyntaxError: (unicode error)‘utf-8’ codec can’t decode 错误的解决办法》​​一样的办法解决就可以了。