How to read a file as binary or hex "string" so that I can do regex search?

Joined
Dec 19, 2024
Messages
7
Reaction score
0
For example,
If I open a file using hex editor, it showed
3C 47 23 56 59 59 66 38 38 5C 67 3A 5A 70 29 32 47 25 28 63 5D 33 32 39 69 30 58 53 2B 4B 44 61 45 27 7A 3F 21 64 76 5B 54 5D 28 46 75 7A 52 5F

How can I get it as "string"?

Should I do below?
---------------------------------------------
hfile1 = open("example1.txt", "rb")
bfile1 = hfile1.read()
----------------------------------------------

But if I use my code above, then I search regex using my code below:
----------------------------------------------
afile1 = re.findall('[0-9A-Fa-f]{2}', bfile1)
----------------------------------------------

There will be error:
TypeError: cannot use a string pattern on a bytes-like object

Then If I modify my regex search using below:
----------------------------------------------
afile1 = re.findall(b'[0-9A-Fa-f]{2}', bfile1)
----------------------------------------------

The regex search result will do regex to String part (Decoded Text) of hex editor:
<G#VYYf88\g:Zp)2G%(c]329i0XS+KDaE'z?!dv[T](FuzR_

So the result is not as I expected

Thank You
 
Joined
Jul 4, 2023
Messages
527
Reaction score
70
Have you tried it this way?
Python:
with open("example1.txt", "rb") as hfile1:
    bfile1 = hfile1.read()

# Convert the binary data to a hexadecimal string
hex_string = bfile1.hex()

print(hex_string)

or but I am not 100% sure about this code, because it decodes the bytes to a string if the file is text-based
Python:
afile1 = re.findall(r'[0-9A-Fa-f]{2}', bfile1.decode('utf-8', errors='ignore'))
 
Joined
Dec 19, 2024
Messages
7
Reaction score
0
Have you tried it this way?
Python:
with open("example1.txt", "rb") as hfile1:
with open("example1.txt", "rb") as hfile1:
    bfile1 = hfile1.read()

# Convert the binary data to a hexadecimal string
hex_string = bfile1.hex()

print(hex_string)

or but I am not 100% sure about this code, because it decodes the bytes to a string if the file is text-based
Python:
afile1 = re.findall(r'[0-9A-Fa-f]{2}', bfile1.decode('utf-8', errors='ignore'))
I will try
what is the difference between
--------------------------------------------------------------------------------------
with open("example1.txt", "rb") as hfile1:
bfile1 = hfile1.read()
--------------------------------------------------------------------------------------
and
--------------------------------------------------------------------------------------
hfile1 = open("example1.txt", "rb")
bfile1 = hfile1.read()
--------------------------------------------------------------------------------------
oh yes, I also want to ask
How can I do this:
I want to compare every two hex code from two files then, all different hex code from both files will be written in text file
 
Joined
Jul 4, 2023
Messages
527
Reaction score
70
what is the difference between
--------------------------------------------------------------------------------------
with open("example1.txt", "rb") as hfile1:
bfile1 = hfile1.read()
--------------------------------------------------------------------------------------
and
--------------------------------------------------------------------------------------
hfile1 = open("example1.txt", "rb")
bfile1 = hfile1.read()

Using with open (Context Manager)

Python:
with open("example1.txt", "rb") as hfile1:
    bfile1 = hfile1.read()
  1. Automatic Resource Management:
    The with open statement is a context manager. It automatically handles resource management by ensuring the file is properly closed when the block is exited, even if an error occurs.
  2. Cleaner Code:
    No need to explicitly call hfile1.close(). The file will be closed once the with block ends.
  3. Error Safety:
    If an exception occurs during the block execution, the file will still be closed properly.
  4. Preferred Practice:
    Recommended for file handling because it reduces the chances of resource leaks.
Use with open unless you have a specific reason not to. It's concise, safer, and handles file management automatically.

Python:
# Example 1: Database connection management
import sqlite3

with sqlite3.connect("example.db") as conn:
    # Connect to a SQLite database and close the connection automatically
    cursor = conn.cursor()
    cursor.execute("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, name TEXT)")
    cursor.execute("INSERT INTO test (name) VALUES ('Sample Name')")
    conn.commit()

# Example 2: Threading lock
import threading

lock = threading.Lock()
with lock:
    # Automatically acquire and release a threading lock
    print("Thread-safe code execution.")

# Example 3: Working with ZIP files
import zipfile

with zipfile.ZipFile("example.zip", "w") as zip:
    # Open a ZIP file and close it automatically
    zip.writestr("example.txt", "This is an example inside a ZIP archive.")

# Example 4: Temporary file management
import tempfile

with tempfile.TemporaryFile() as temp_file:
    # Create a temporary file and delete it automatically after use
    temp_file.write(b"This is temporary content.")
    temp_file.seek(0)
    print(temp_file.read())

# Example 5: HTTP requests
import requests

with requests.get("https://example.com") as response:
    # Automatically manage the HTTP connection
    print(response.text[:100])  # Print the first 100 characters of the response

# Example 6: Timing execution
import time

class Timer:
    def __enter__(self):
        self.start = time.time()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.end = time.time()
        print(f"Execution time: {self.end - self.start:.2f} seconds")

with Timer():
    # Measure the time of this block
    sum(range(10000000))



BTW, check this out:
 
Last edited:

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,073
Messages
2,570,539
Members
47,195
Latest member
RedaMahuri

Latest Threads

Top