Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (19.9k points)

I want to generate two digit counter and write them in a file and do something for each instance. Each digit is actually a byte represented by a hex value. So, I want to

0- Open the file for write

1- Generate 0x00,0x00

2- write that in a file.

3- Close the file and process it

and this continues for 0x00,0x01 and 0x00,0x02 and ... and 0x01,0x00 until 0xff,0xff.

I have written a sample like this

for i in range(2):

    f = open("file.txt", "w")

    f.write("0x{:02x},".format(i))

    for j in range(3):

        f.write("0x{:02x}".format(j))

        f.close()

        # run a cmd and pass this file as an argument

Ranges should be 256 in the final script. Nonetheless, problem is that, when the file is closed in the inner loop, it can not be ready for the second digit in the next inner iteration. Therefore, that code only works for i=j=0 and when i=0,j=1 it is unable to write the hex value into the file.

How can I fix that?

1 Answer

0 votes
by (25.1k points)

You are facing this issue because you are closing the file at the end of inner j loop but not opening it again: You can do it like this:

for i in range(2):

    for j in range(3):

    f = open("file.txt", "w+")

    f.write("0x{:02x},".format(i))

    f.write("0x{:02x}".format(j))

    f.close()

    # run a cmd and pass this file as an argument

Related questions

0 votes
1 answer
asked Sep 25, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer
asked Oct 10, 2019 in Python by Sammy (47.6k points)

Browse Categories

...