pengowen123
pengowen123

Reputation: 1017

Read binary numbers from a file

I am trying to read from a file that contains a list of binary numbers in this format: 0b1111; 0b1010; 0b0101 // 0b1110; 0b0010 and so on. Then, I want to append each section separated by "//" to a list. Each of those sections should be turned into a list that contains all the numbers in the section separated by ";". I finally got the code to work, but after modifying a completely different and unrelated code and reversing the changes, now it breaks. Here is the code I am using currently, as after trying to fix the issue I do not have the original code:

programLoad = open("programs.txt", "r")
programLoadList = programLoad.read()
programList = [p for p in programLoadList.split("//")]
programLoad.close()

for index in range(len(programList)):
    programList[index] = [int(n, 2) for n in programList[index].split(";")]

I will not put the file here because it is really big. However, all the numbers follow the correct format and when running it fails on the list comprehension with the error "invalid literal for int base 2".

If you need more information to help I will be glad to supply it.

Upvotes: 0

Views: 261

Answers (2)

Rohith Uppala
Rohith Uppala

Reputation: 177

I think this will work. Just treat every binary representation as a string and omit first two characters and convert remaining text to integer.

programLoad = open("programs.txt", "r")
programLoadList = programLoad.read()
programList = [p for p in programLoadList.split("//")]
programLoad.close()

for index in range(len(programList)):
    print programList[index]
    programList[index] = [int(n[2:], 2) for n in programList[index].split(";")]

print programList

Upvotes: 0

Andy Hayden
Andy Hayden

Reputation: 375575

You can do this in a single list comprehension:

In [11]: [[int(b, 2) for b in line.split(";")] for line in program_list.split("//")]
Out[11]: [[15, 10, 5], [14, 2]]

Upvotes: 1

Related Questions