0

This is just a part of my script :

This script is to extract data from a logfile to a text file.

self.cut.start_line='test started'

def extract_data(self):
    data=None
    for line in self.file_content:
        if data is None: 
            if self.start_line in line:   #search for 'test started'
                data=[]     
        elif self.end_line in line:    
            break   
        else:       
            data.append(line)
    return data

I wrote this script using Python 2 but when I run in Python 3 it shows:

>>> if self.start_line in line:   #search for 'test started'
TypeError: a bytes-like object is required, not 'str'

Can somebody help me?

2
  • 1
    Make start_line a byte string: b'test started' Commented Jul 7, 2020 at 9:39
  • 1
    self.file_content is bytes. stackoverflow.com/questions/33054527/… Commented Jul 7, 2020 at 9:40

3 Answers 3

1

This is arising because while reading the logfile, you must have openedn the file in "rb" mode. This means in binary mode.

Now while doing comparison also it is asking to provide a binary substring for checking.

Now, you can solve this in 2 ways :

  1. Either convert your search string into binary.
self.cut.start_line=b'test started'
  1. Open the logfile for reading in simple mode, i.e., not binary mode [use "r" instead of "rb"].
Sign up to request clarification or add additional context in comments.

1 Comment

my reading mode is in 'r' mode btw. okay i will try to do the first way. thanks!
0

line must be a str or start_line must be a bytes object

Two options:

Use b'test started'

self.cut.start_line=b'test started'

def extract_data(self):
    data=None
    for line in self.file_content:
        if data is None: 
            if self.start_line in line:   #search for 'test started'
                data=[]     
        elif self.end_line in line:    
            break   
        else:       
            data.append(line)
    return data

Use line.decode()

self.cut.start_line='test started'

def extract_data(self):
    data=None
    for line in self.file_content:
        line = line.decode()
        if data is None: 
            if self.start_line in line:   #search for 'test started'
                data=[]     
        elif self.end_line in line:    
            break   
        else:       
            data.append(line)
    return data

1 Comment

Thank you! i tried to do the first option. works well for my script.
0

Use the encode() function to encode the string to bytes.

self.cut.start_line='test started'.encode()

If you want to get back the original string, use the decode() function. If self.cut.start_line is the encoded text, then

self.cut.start_line.decode()

will give back the original string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.