Python Forum
How to convert while loop to for loop in my code?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to convert while loop to for loop in my code?
#1
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
Reply
#2
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
Reply
#3
(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?
Reply
#4
Looking at your code I think you want to read the files 4 bytes at a time and compare the bytes objects
Reply
#5
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'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  in c# create a loop counting from 0 to 5, consecutively Frankd 19 2,098 Apr-01-2025, 12:46 PM
Last Post: Frankd
  really new to python want to know how to do a loop pentopdmj 6 1,569 Mar-09-2025, 12:59 PM
Last Post: snippsat
  knowing for loop position in a list medic5678 4 664 Jan-31-2025, 04:19 PM
Last Post: perfringo
  Run this once instead of a loop, do I need the 'calibration' steps? duckredbeard 2 718 Jan-28-2025, 04:55 PM
Last Post: duckredbeard
  Error loop with Chatgpt sportak12 0 490 Jan-14-2025, 12:04 PM
Last Post: sportak12
  How to get keep information in a loop ginod 4 872 Dec-11-2024, 01:32 AM
Last Post: deanhystad
  Regarding The For Loop Hudjefa 5 1,442 Nov-15-2024, 01:02 PM
Last Post: deanhystad
  For Loop beginner agoldav 2 711 Nov-05-2024, 12:51 AM
Last Post: agoldav
  A question about 'Event loop is closed' fc5igm 3 5,090 Oct-01-2024, 09:12 AM
Last Post: skdaro
  For Loop assigns only the latest value from List Caliban86 3 1,181 Sep-22-2024, 02:47 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020