Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Searching a csv for hex data with python

Tags:

python

csv

I have a csv file which has 3 columns. I am trying to search through the second column for a specific value (hex values) and read the next entry over in that line (column 3). The format is similar to the below:

Text1,  0x04d0a053, value1
Text2,  0x04d01053, value2
Text3,  0x04d03053, value3
Text4,  0x04d05053, value4
Text5,  0x04d00053, value5
Text6,  0x04d02053, value6
Text7,  0x04d04053, value7
Text8,  0x04413053, value8

I have no problem searching and reading the last value (0x04413053) and printing 'value8'. However, when I attempt to search for any of the first 7 entries nothing is read back ([] on the output). My code is below, anyone have an idea of what the bug might be?

fileInput = 'mycsv.csv'
column0 = 0
column1 = 1
column2 = 2

#reads correctly
hexvalue = hex(0x04413053)
with open(fileInput, 'r') as file:
  reader = csv.reader(file)
  entry = [line[column2] for line in reader if line[column1] == hexvalue]
  print entry

#does not read correctly
hexvalue = hex(0x04d0a053)
with open(fileInput, 'r') as file:
  reader = csv.reader(file)
  entry = [line[column2] for line in reader if line[column1] == hexvalue]
  print entry
like image 542
Hoser Avatar asked Feb 20 '23 08:02

Hoser


2 Answers

hex(0x 0 4413053) is "0x4413053"

You should probably do the inverse, i.e.

int(line[clolumn1], 16) == 0x04413053
like image 112
MK. Avatar answered Feb 25 '23 15:02

MK.


In both cases you read through all of the values in the for statement, you should not. Just do:

for line in reader:
    if line[column1] == hexvalue:
        entry = line[column2]
        break # efficient!
print entry
like image 21
Anthon Avatar answered Feb 25 '23 15:02

Anthon