【问题标题】:Python - TypeError: expected string or bytes-like objectPython - TypeError:预期的字符串或类似字节的对象
【发布时间】:2017-08-29 01:28:58
【问题描述】:

我有以下代码:

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

这是为什么呢?我该如何解决这个问题?

谢谢。

【问题讨论】:

    标签: python for-loop


    【解决方案1】:

    你在这一行使用二进制模式'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()
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 2020-07-08
    • 2018-05-04
    • 1970-01-01
    相关资源
    最近更新 更多