2017-04-04 1 views
0

나는이 다음 코드 :파이썬 - 형식 오류 : 예상 문자열이나 바이트와 같은 객체

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 

입니다? 문제를 어떻게 해결할 수 있습니까?

감사합니다.

답변

2

전체 파일은이 행의 이진 모드 'rb'을 사용하고 있습니다.

with open(File, mode='rb') as file: 
    readFile = file.read() 

이렇게하면 readFile을 바이트 배열로 만들고, readFile을 다음과 같이 반복하면 단일 바이트가 제공됩니다. 어떤 파이썬은 정수라고 가정합니다.

>> 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() 
+0

친절한 답변을 보내 주셔서 감사합니다. TypeError : 바이트 형 객체에 문자열 패턴을 사용할 수 없습니다. – Simplicity

+2

위의 오류에 대한 대답입니다. 그것은 내가 문자열 패턴 대신 바이트 패턴을 사용해야합니다 : http://stackoverflow.com/questions/5184483/python-typeerror-on-regex – Simplicity

+1

@ Simplicity 오 죄송합니다, 네가 할 수있는 또는 텍스트 파일에서 읽을 수 파일에 문자열이 있다면''rb''를''r''로 바꾸면됩니다. – umutto

관련 문제