【问题标题】:Python: searching csv and return entire rowPython:搜索csv并返回整行
【发布时间】:2014-11-22 19:27:24
【问题描述】:

我找不到更好的地方来问我的问题。我正在学习 Python 并尝试创建如下脚本。

1) 应该可以搜索 csv 文件。

2) 如果找到匹配,则返回整行。

我的 csv:

Product,Scan,Width,Height,Capacity
LR,2999,76,100,17.5
RT,2938,37,87,13.4

如果我搜索 2938 为例,整行返回如下:

Product: RT
Scan: 2938
Width: 37
Height: 87
Capacity: 13,4

到目前为止我有:

csvFile = getComponent().filePath
pos = csvFile.rfind('Desktop\\')
csvFile = csvFile[:pos] + 'programm\\products.csv'

myfile = open(csvFile)
myfile.seek(0)
for line in myfile.split('\n'):
    data = line.split(',')
    print data
    if data[2] == agv_O_Cal.value and data[3] == agv_O_Mod.value:
        print 'found: value = %s' %agv_O_Cal.value, agv_O_Mod.value
        Product = data[5]
        Scan = data[6]
        Width = data[7]
        Height = data[9]
        Capacity = data[10]
        print , Product, Scan, Width, Height, Capacity

解决方案不起作用。

【问题讨论】:

  • 你当前的输出是什么?
  • 缩进错误:意外缩进
  • 刚刚添加了答案,如果没有意义,请在此处评论
  • 我编辑你的代码。试试看。

标签: python csv search return row


【解决方案1】:

你可以像这样使用csv 模块:

import csv
reader = csv.reader(open(csvFile, 'r'))
for data in reader:
    #list index start from 0, thus 2938 is in data[1]
    if data[1] == agv_O_Cal.value and data[3] == agv_O_Mod.value:
        #do somethinngs

【讨论】:

    【解决方案2】:
    #!/usr/bin/python
    
    import csv
    import sys
    
    #input number you want to search
    number = raw_input('Enter number to find\n')
    
    #read csv, and split on "," the line
    csv_file = csv.reader(open('test.csv', "r"), delimiter=",")
    
    
    #loop through the csv list
    for row in csv_file:
        #if current rows 2nd value is equal to input, print that row
        if number == row[1]:
             print (row)
    

    【讨论】:

    • 我的 csv 文件是否应该与 py 文件位于同一文件夹中?
    • 是的,当然用你的 csv 名称替换“test.csv”
    • 输入号码以查找 2938 Traceback(最近一次调用最后一次):文件“C:\Users\MyName\Desktop\programm\phy2.py”,第 5 行,在 csv_file = csv. reader(open('autod.csv', "rb"), delimiter=",") NameError: name 'csv' is not defined
    • 如何输出为列表?之前的描述(例如产品:Xcl,其中 Xcl 是取自 csv 的值)和之后的值。
    • 不理解您的问题,但请按照社区标准投票/接受我的回答。
    猜你喜欢
    • 1970-01-01
    • 2013-02-26
    • 1970-01-01
    • 2020-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-29
    • 2012-01-07
    相关资源
    最近更新 更多