首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python:搜索csv并返回整行

Python:搜索csv并返回整行
EN

Stack Overflow用户
提问于 2014-09-28 14:43:46
回答 2查看 67K关注 0票数 9

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

1)应该能够搜索csv文件。

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

我的csv:

代码语言:javascript
复制
Product,Scan,Width,Height,Capacity
LR,2999,76,100,17.5
RT,2938,37,87,13.4

如果我搜索2938作为示例,则返回整行,如下所示:

代码语言:javascript
复制
Product: RT
Scan: 2938
Width: 37
Height: 87
Capacity: 13,4

到目前为止,我有:

代码语言:javascript
复制
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

这个解决方案不起作用。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-09-28 15:04:04

代码语言:javascript
复制
#!/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)
票数 10
EN

Stack Overflow用户

发布于 2014-09-28 14:53:52

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

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/26082360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档