w3resource

Python Function: Search bytes sequence in file

Python Bytes and Byte Arrays Data Type: Exercise-9 with Solution

Write a Python function that searches for a bytes sequence within a file opened in byte mode.

Sample Solution:

Code:

import io
def search_bytes_in_file(file_path, match_bytes):
  with io.open(file_path, mode='rb') as file:
    for line in file:
      if match_bytes in line:
        print(f"Match found in file {file_path}")
        return True
    else:
      return False

# Example usage
match = b'foobar'  
result = search_bytes_in_file('fontawesome-webfont.bin', match)
if result:
  print("Match found") 
else:
  print("No match")

Output:

No match

Explanation:

In the exercise above -

  • Open file in byte mode 'rb'
  • Iterate over the file line-by-line as bytes
  • Use the 'in' operator to check if match_bytes is present
  • Return True if match found, False otherwise
  • Can search any bytes sequence like encoded data

Flowchart:

Flowchart: Python Function: Search bytes sequence in file.

Previous: Compress and decompress bytes using zlib.
Next: Convert bytearray to bytes

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/extended-data-types/python-extended-data-types-bytes-bytearrays-exercise-9.php