r/pythonhelp • • Apr 26 '20

My file output is incorrect?

I am currently learning Python, and the script I wrote 'mostly' works, but the output is wrong. Here's the code.

The output in the console has significantly more lines than the .txt file that was output. Is there some kind of limit to how much can be written to a file?

0 Upvotes

6 comments sorted by

1

u/socal_nerdtastic Apr 26 '20

Is there some kind of limit to how much can be written to a file?

No. How are you checking the output? You need to close the ouput file if you want to check it with python still running.

What is this code supposed to do?

1

u/Mallos42 Apr 26 '20

It is supposed to search a rom for every instance of the binary string 0xB800000000000000 and write the offset to file. It prints EVERY offset to the console with no problem, but the text file is missing over 200 lines compared to the console output.

1

u/socal_nerdtastic Apr 26 '20

Did you try closing the file? Try adding

offsetOutput.close()

at the end of your program.

1

u/Mallos42 Apr 26 '20

I put it at the very end and got this error: ValueError: I/O operation on closed file.

EDIT: My indention was one off, so I cleared that error. I'm waiting on it to finish running right now.

EDIT2: That fixed it. Thank you!!

1

u/socal_nerdtastic Apr 26 '20

Put it at the very end, but completely unindented. If you share your code as text instead of an image I can edit your code for you.

1

u/socal_nerdtastic Apr 26 '20

FWIW you have made this much more complex than it needs to be. You should treat this as 3 individual and completely distinct steps. Here's how I would write it:

search_for = b'\xB8\x00\x00\x00\x00\x00\x00\x00'
rom_file = "quest.z64"
output_file = "offsets.txt"

# load file data
with open(rom_file, 'rb') as f:
    data = f.read()

# locate offsets
offsets = []
idx=-1
while (idx := data.find(search_for, idx+1)) > 0:
    offsets.append(idx)
    print(idx)

# write data
with open(output_file, 'w') as f:
    for idx in offsets:
        print(idx, file=f) # write to file

Probably a lot faster this way too.