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

2024-04-26 14:45:46 发布

您现在位置:Python中文网/ 问答频道 /正文

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

如何扩展下面的代码以只针对productsell文件中的'ID'和'Name'列?你知道吗

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.csvproductsOld.csv


Tags: 文件csvtexttitlestyleaswithopen
1条回答
网友
1楼 · 发布于 2024-04-26 14:45:46

看看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)

你知道吗产品销售.csv你知道吗

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

管道新2.csv

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

你知道吗更新.csv你知道吗

id,name
3,cc

相关问题 更多 >