使用python定位到csv文件中的特定列

时间:2019-04-15 09:45:43

标签: python

我有以下python代码。我想比较两个csv文件,但是我只想比较第二个CSV文件中的2列。

如何将以下代码扩展为仅针对productsOld文件中的“ ID”和“名称”列?

import ctypes  # An included library with Python install.
def Mbox(title, text, style):
    return ctypes.windll.user32.MessageBoxW(0, text, title, style)

try:
    with open('pipeNew2.csv', 'r') as t1, open('productsOld.csv', 'r') as t2:
        fileone = t1.readlines()
        filetwo = t2.readlines()



    with open('update.csv', 'w') as outFile:
        for line in filetwo:
            if line not in fileone:
                outFile.write(line)
    Mbox('Complete', 'Compairson Complete', 0)
except (ValueError,IOError) as err:
        Mbox('Error',(str(err)),0)

我尝试过的方法-无论如何,这只会打印出所有文件,并且打印在同一行上

import ctypes  # An included library with Python install.
import csv
def Mbox(title, text, style):
    return ctypes.windll.user32.MessageBoxW(0, text, title, style)

try:
    with open('pipeNew2.csv', 'r') as t1, open('productsOld.csv', 'r') as t2:
        fileone = t1.readlines()
        filetwo = t2.readlines()



    with open('update.csv', 'w') as outFile:
        newFile = csv.DictReader(filetwo)
        for row in newFile:
            if row['id'] not in fileone:
                outFile.write(str(row))
    Mbox('Complete', 'Compairson Complete', 0)
except (ValueError,IOError) as err:
        Mbox('Error',(str(err)),0)

pipeNew2.csv productsOld.csv

1 个答案:

答案 0 :(得分:1)

看看csv内置模块。

示例:

import ctypes  # An included library with Python install.
import csv


def Mbox(title, text, style):
    return ctypes.windll.user32.MessageBoxW(0, text, title, style)


try:
    f1n = 'pipeNew2.csv'
    fn1 = ['catalogid', 'id', 'name']

    f2n = 'productsOld.csv'
    fn2 = ['id', 'name']

    with open(f1n, 'r', newline='') as t1, open(f2n, 'r', newline='') as t2:
        f1 = [line['id'] + line['name'] for line in csv.DictReader(t1, delimiter=',', fieldnames=fn1)]
        f2 = csv.DictReader(t2, delimiter=',', fieldnames=fn2)

        with open('update.csv', 'w+', newline='') as outFile:
            writer = csv.DictWriter(outFile, fieldnames=fn2)
            writer.writeheader()  # if csv have header

            for oldRow in f2:
                if not oldRow['id'] + oldRow['name'] in f1:
                    writer.writerow(oldRow)

except (ValueError, IOError) as err:
    Mbox('Error', (str(err)), 0)

productsOld.csv

id,name
1,aa
2,bb
3,cc
4,dd

pipeNew2.csv

catalogid,id,name
a,1,aa
b,2,bb
c,4,dd

update.csv

id,name
3,cc