我有以下代码:
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
为什么?我该如何解决这个问题?
感谢。
答案 0 :(得分:2)
您正在使用此行中的二进制模式'rb'
阅读整个文件;
with open(File, mode='rb') as file:
readFile = file.read()
这样就使你的readFile成为一个字节数组,当你以下面的方式遍历readFile时,它会给你一个字节。哪个python假设是一个整数。
>> for line in readFile:
>> print(line)
>> print(type(line))
116
<class 'int'>
104
<class 'int'>
105
<class 'int'>
...
我认为你的意思是逐行阅读文件;
with open(File, mode='rb') as file:
readFile = file.readlines()