简体   繁体   English

搜索CSV文件

[英]Searching a CSV file

I need to filter and do some math on data coming from CSV files. 我需要对来自CSV文件的数据进行过滤并做一些数学运算。

I've wrote a simple Pyhton script to isolate the rows I need to get (they should contain certain keywords like "Kite"), but my script does not work and I can't find why. 我编写了一个简单的Pyhton脚本来隔离需要获取的行(它们应包含诸如“ Kite”之类的某些关键字),但是我的脚本无法正常工作,而且我找不到原因。 Can you tell me what is wrong with it? 你能告诉我这是怎么回事吗? Another thing: once I get to the chosen row/s, how can I point to each (comma separated) column? 另一件事:一旦到达选定的行,如何指向每个(逗号分隔)列?

Thanks in advance. 提前致谢。

R. R.

import csv

with open('sales-2013.csv', 'rb') as csvfile:
    sales = csv.reader(csvfile)
    for row in sales:
        if row == "Kite":
            print ",".join(row)

To find the rows than contain the word "Kite", then you should use 要查找包含单词“ Kite”的行,则应使用

for row in sales:   # here you iterate over every row (a *list* of cells)
    if "Kite" in row:
        # do stuff

Now that you know how to find the required rows, you can access the desired cells by indexing the rows. 现在,您知道如何查找所需的行,可以通过对行进行索引来访问所需的单元格。 For example, if you want to select the second cell of a row, you simply do 例如,如果要选择一行的第二个单元格,则只需执行

cell = row[1]  # remember, indexes start with 0

You are reading the file in bytes. 您正在读取文件(以字节为单位)。 Change the open('filepathAndName.csv, 'r') command or convert your strings like "Kite".encode('UTF-8') . 更改open('filepathAndName.csv, 'r')命令或转换字符串,例如"Kite".encode('UTF-8') The second mistake could be that you are looking for a line with the word "Kite", but if "Kite" is a substring of that line it will not be found. 第二个错误可能是您正在寻找带有单词“ Kite”的行,但是如果“ Kite”是该行的子字符串,则找不到该行。 In this case you have to use if "Kite" in row: . 在这种情况下,您必须if "Kite" in row:使用if "Kite" in row:

with open('sales-2013.csv', 'rb') as csvfile: # <- change 'rb' to 'r'
    sales = csv.reader(csvfile)
    for row in sales:
        if row == "Kite": # <- this would be better: if "Kite" in row:
            print ",".join(row)

Read this: https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files 阅读此内容: https : //docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM