0
我有以下代码:的Python - 类型错误:预期字符串或字节状物体
import re
meshTerm = {}
meshNumber = {}
File = 'file.bin'
with open(File, mode='rb') as file:
readFile = file.read()
outputFile = open('output.txt', 'w')
for line in readFile:
term= re.search(r'MH = .+', line)
print(term)
当我运行代码,我收到以下错误:
Traceback (most recent call last):
File "myFile.py", line 13, in <module>
term = re.search(r'MH = .+', line)
File "C:\Python35\lib\re.py", line 173, in search
return _compile(pattern, flags).search(string)
TypeError: expected string or bytes-like object
这是为什么?我该如何解决这个问题?
感谢。
感谢您的回复。我现在得到这个错误:TypeError:不能在字节状对象上使用字符串模式 – Simplicity
这回答了上述错误。它似乎我应该使用字节模式,而不是字符串模式:http://stackoverflow.com/questions/5184483/python-typeerror-on-regex – Simplicity
@Simplicity哦对不起,是的,你可以做到这一点,或阅读文本文件模式中,如果文件中有字符串,则将''rb''更改为''r''。 – umutto