Python CSV特定行提取

时间:2015-02-28 21:34:44

标签: python csv

我有两个CSV文件,我希望python打开file1.csv并从该文件中读取第7行,并在整个file2.csv上查找相同的二进制代码。

这是我到目前为止所做的,但它不起作用:

import csv

a = open('file1.csv','r').readline[7]


with open('file2.csv') as infile:
    for row in csv.reader(infile):
        if row[1:] == a: # This part is fine because i want to skip the first row 
            print row[0], ','.join(row[1:])

1 个答案:

答案 0 :(得分:2)

看起来您需要了解python csv library如何运作:)您可能还想了解list slicing的工作原理。我会根据我对你的问题的理解来帮助你。

我有同样的问题@oliver-w但我只是假设您的'csv'文件只有一列。

import csv

with open('file1.csv', 'r') as file1:
    # this is the value you will be searching for in file2.csv
    # you might need to change this to [6] if there is no header row in file1.csv
    val = list(csv.reader(file1))[7]

with open('file2.csv', 'r') as file2:
    reader = csv.reader(file2)
    reader.next() # this skips the first row of the file
    # this iteration will start from the second row of file2.csv
    for row in reader:
        if row[0] == val:
            # your question doesn't clarify what your actual purpose is
            # so i don't know what should be here