4

我有一个 csv 文件,它有 3 列。我正在尝试在第二列中搜索特定值(十六进制值)并读取该行中的下一个条目(第 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

搜索和读取最后一个值(0x04413053)并打印“value8”没有问题。但是,当我尝试搜索前 7 个条目中的任何一个时,不会回读任何内容(输出中的 [])。我的代码在下面,有人知道错误可能是什么吗?

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
4

5 回答 5

7

十六进制(0x 0 4413053)是“0x4413053”

你可能应该做相反的事情,即

int(line[clolumn1], 16) == 0x04413053
于 2012-05-25T20:31:23.017 回答
1

在这两种情况下,您都不应该通读 for 语句中的所有值。做就是了:

for line in reader:
    if line[column1] == hexvalue:
        entry = line[column2]
        break # efficient!
print entry
于 2012-05-25T20:36:09.477 回答
0

除了MK 的最佳答案中指出的类型问题外,我注意到您提出的 csv 示例有一些空白问题会破坏您的代码。这是我的解决方案:

fileInput = 'mycsv.csv'

# Sniff csv format to easily avoid whitespace issue.
with open(fileInput, 'r') as afile: # 'file' is a python keyword. Best to avoid overriding it.
    snift = csv.Sniffer().sniff(afile.readline())

# get the answers in a single pass at the file.
# If that doesn't work for you, fine, but try to avoid opening the file twice.
hexvalues = set([0x04413053, 0x04d0a053])
with open(fileInput, 'r') as afile:
  reader = csv.reader(afile, dialect=snift)
  entries = [line[2] for line in reader if int(line[1], 16) in hexvalues]

print '\n'.join(entries)
于 2012-05-25T20:58:47.457 回答
0

问题在于 if 条件。您不是在比较相同的值。

  hex_string = "0x04413053"
  with open(fileInput, 'r') as file:
    reader = csv.reader(file)
    entry = [line[column2] for line in reader if int(line[column1], 16) == int(hex_string, 16)]
    print entry

上面的代码显示您应该比较相同的类型。这可以重写为:(
仅供参考:int(line[column1], 16)将字符串转换为十六进制)

  hexvalue = 0x04413053
  with open(fileInput, 'r') as file:
    reader = csv.reader(file)
    entry = [line[column2] for line in reader if int(line[column1], 16) == hexvalue]
    print entry
于 2012-05-25T21:00:07.677 回答
0

在玩弄了所有示例之后,我得到了以下工作代码:

Anthon 是正确的,因为我只需要对列表中的值进行一次排序,就我而言,不会有重复的模式。我确实必须修改 Anthon 以添加来自 MK 的输入以找到我正在搜索的十六进制值。

谢谢您的帮助。

hexvalue = 0x04d03053
with open(fileInput, 'r') as file:
    reader = csv.reader(file)    
    for line in reader:
        if int(line[column1], 16) == hexvalue:
            entry = line[column2]
            break # efficient!
    print entry
于 2012-05-25T21:26:13.970 回答