我有一个有3列的csv文件.我试图在第二列中搜索特定值(十六进制值)并读取该行中的下一个条目(第3列).格式类似于以下内容:
Text1, 0x04d0a053, value1
Text2, 0x04d01053, value2
Text3, 0x04d03053, value3
Text4, 0x04d05053, value4
Text5, 0x04d00053, value5
Text6, 0x04d02053, value6
Text7, 0x04d04053, value7
Text8, 0x04413053, value8
Run Code Online (Sandbox Code Playgroud)
我没有问题搜索和读取最后一个值(0x04413053)并打印'value8'.但是,当我尝试搜索前7个条目中的任何一个时,不会读回任何内容(输出中的[]).我的代码如下,任何人都知道bug可能是什么?
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
Run Code Online (Sandbox Code Playgroud)
十六进制(0x 0 4413053)是"0x4413053"
你应该做反过来,即
int(line[clolumn1], 16) == 0x04413053
Run Code Online (Sandbox Code Playgroud)