Python Forum

Full Version: How to convert while loop to for loop in my code?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a working script in python like this:
import re

handle_file1 = open("example1.so", "rb")
hex_file1 = handle_file1.read().hex().upper()
handle_file1.close()

handle_file2 = open("example2.so", "rb")
hex_file2 = handle_file2.read().hex().upper()
handle_file2.close()

array_file1 = re.findall('[0-9A-Fa-f]{2}', hex_file1)
array_file2 = re.findall('[0-9A-Fa-f]{2}', hex_file2)

i = 0
while i < len(array_file1):
    if array_file1[i] != array_file2[i]:
        if i % 4 == 0:
            print(array_file1[i] + array_file1[i + 1] + array_file1[i + 2] + array_file1[i + 3] + "\t" + array_file2[i] + array_file2[i + 1] + array_file2[i + 2] + array_file2[i + 3])
            i += 4
        elif i % 4 == 1:
            print(array_file1[i - 1] + array_file1[i] + array_file1[i + 1] + array_file1[i + 2] + "\t" + array_file2[i - 1] + array_file2[i] + array_file2[i + 1] + array_file2[i + 2])
            i += 3
        elif i % 4 == 2:
            print(array_file1[i - 2] + array_file1[i - 1] + array_file1[i] + array_file1[i + 1] + "\t" + array_file2[i - 2] + array_file2[i - 1] + array_file2[i] + array_file2[i + 1])
            i += 2
        elif i % 4 == 3:
            print(array_file1[i - 3] + array_file1[i - 2] + array_file1[i - 1] + array_file1[i] + "\t" + array_file2[i - 3] + array_file2[i - 2] + array_file2[i - 1] + array_file2[i])
            i += 1
    else:
        i += 1
How can I convert the while loop into for loop?
I have AutoIT script like this:

        For $i = 1 To UBound($aFile1, $UBOUND_ROWS)-1
            If $aFile1[$i] <> $aFile2[$i] Then
                If Mod($i, 4) = 0 Then
                    FileWrite(@ScriptDir & '\' & 'Result.txt', $aFile1[$i] & ' ' & $aFile1[$i+1] & ' ' & $aFile1[$i+2] & ' ' & $aFile1[$i+3] & '    ' & $aFile2[$i] & ' ' & $aFile2[$i+1] & ' ' & $aFile2[$i+2] & ' ' & $aFile2[$i+3] & @CRLF)
                    $i = $i + 4
                ElseIf Mod($i, 4) = 1 Then
                    FileWrite(@ScriptDir & '\' & 'Result.txt', $aFile1[$i-1] & ' ' & $aFile1[$i] & ' ' & $aFile1[$i+1] & ' ' & $aFile1[$i+2] & '    ' & $aFile2[$i-1] & ' ' & $aFile2[$i] & ' ' & $aFile2[$i+1] & ' ' & $aFile2[$i+2] & @CRLF)
                    $i = $i + 3
                ElseIf Mod($i, 4) = 2 Then
                    FileWrite(@ScriptDir & '\' & 'Result.txt', $aFile1[$i-2] & ' ' & $aFile1[$i-1] & ' ' & $aFile1[$i] & ' ' & $aFile1[$i+1] & '    ' & $aFile2[$i-2] & ' ' & $aFile2[$i-1] & ' ' & $aFile2[$i] & ' ' & $aFile2[$i+1] & @CRLF)
                    $i = $i + 2
                ElseIf Mod($i, 4) = 3 Then
                    FileWrite(@ScriptDir & '\' & 'Result.txt', $aFile1[$i-3] & ' ' & $aFile1[$i-2] & ' ' & $aFile1[$i-1] & ' ' & $aFile1[$i] & '    ' & $aFile2[$i-3] & ' ' & $aFile2[$i-2] & ' ' & $aFile2[$i-1] & ' ' & $aFile2[$i] & @CRLF)
                    $i = $i + 1
                EndIf
            ElseIf $aFile1[$i] = $aFile2[$i] Then
                ContinueLoop
            EndIf
       Next
I want to convert my while loop into for loop
or I simply want to convert my for loop from AutoIT to Python

How to do that?

Thank You
A for loop is the wrong choice if the code body changes the index.

Are you trying to compare binary files? Converting to str and using re is not how I would do this
(Dec-20-2024, 05:19 AM)deanhystad Wrote: [ -> ]A for loop is the wrong choice if the code body changes the index.

Are you trying to compare binary files? Converting to str and using re is not how I would do this

I actually want to automate something like if I compare two file in a hex editor
Do you have any suggestion for me please?
Looking at your code I think you want to read the files 4 bytes at a time and compare the bytes objects
In your first Thread i advice how to get the hex view same as in hex editor.
When it comes to compare 2 files it can be easiest to work with the raw bytes directly and only convert those bytes(to hex) that differ for printing.
Why This is Easiest:
  • No complicated indexing or regex.
  • Works purely at the binary level(Compare byte by byte)
  • Easy to adapt for more specialized output formatting (like printing differences in 4-byte chunks or aligned hex dumps).

Let say i use binary file example in you first thread.
Example1.txt:
Output:
<G#VYYf88\g:Ap)2G%(c]329i0XS+KDaE'z?!dv[T](FuzR_
Change R to Z and add hello.
Example2.txt:
Output:
<G#VYYf88\g:Ap)2G%(c]329i0XS+KDaE'z?!dv[T](FuzZ_hello
So this approach will find all changes and print :02X(hex value in the f-string) out.
def compare_files_hex(file1, file2):
    with open(file1, 'rb') as f1, open(file2, 'rb') as f2:
        data1 = f1.read()
        data2 = f2.read()

    min_len = min(len(data1), len(data2))
    # Compare the overlapping portion of both files
    for n in range(min_len):
        if data1[n] != data2[n]:
            print(f"Offset {n}: {data1[n]:02X} != {data2[n]:02X}")
    # If one file is longer, print the extra bytes as differences
    if len(data1) > min_len:
        # data1 has extra bytes
        for n in range(min_len, len(data1)):
            print(f"Offset {n}: {data1[n]:02X} != (no data in {file2})")
    if len(data2) > min_len:
        # data2 has extra bytes
        for n in range(min_len, len(data2)):
            print(f"Offset {n}: (no data in {file1}) != {data2[n]:02X}")

compare_files_hex("example2.txt", "example1.txt")
Output:
Offset 46: 5A != 52 Offset 48: 68 != (no data in example1.txt) Offset 49: 65 != (no data in example1.txt) Offset 50: 6C != (no data in example1.txt) Offset 51: 6C != (no data in example1.txt) Offset 52: 6F != (no data in example1.txt)
So if eg want to now what hex values 68 65 .... are can use bytes.fromhex()
>>> hex_string = "68"
>>> bytes_obj = bytes.fromhex(hex_string)
>>> bytes_obj
b'h'
>>> hex_string = "65"
>>> bytes_obj = bytes.fromhex(hex_string)
>>> bytes_obj
b'e'
>>> # To str just add decode
>>> bytes_obj.decode()
'e'