Python从Dic查找和替换/附加CSV

时间:2014-06-11 19:28:51

标签: python csv

我有一个包含四列的csv文件。其中一列(第三列)是IP地址。这些知识产权属于某些公司。我正在尝试查找IP地址的实例,并将公司名称APPEND到IP地址的末尾。

CSV示例

   Time,Origination,IP Address, Destination
    6/11/14 14:45,1234567890,1.2.3.4,0987654321

我想要的是什么:

    Time,Origination,IP Address, Destination
    6/11/14 14:45,1234567890,1.2.3.4 **"CUSTOMERNAME"**,0987654321

这是我的代码......这是一团糟。

    import pandas
    import xlrd
    import csv
    import os

    def replace_ip(file, dic):
        spoofingFile = open('spoofing.csv','wb')
        wr = csv.writer(spoofingFile, quoting=csv.QUOTE_ALL)
        for i, j in dic.iteritems():

    ^^^^ I DONT KNOW HOW TO DO THIS! ^^^^^^        


    def csv_from_excel():

        wb = xlrd.open_workbook("C:\\Python27\\Work\\spreadsheet.xlsx")
        sh = wb.sheet_by_name('Sheet1')
        spoofingFile = open('spoofing.csv', 'wb')
        wr = csv.writer(spoofingFile, quoting=csv.QUOTE_ALL)

        for rownum in xrange(sh.nrows):
            wr.writerow(sh.row_values(rownum))

        spoofingFile.close()


    csv_from_excel()
    df = pandas.read_csv('C:\\Python27\\Work\\spoofing.csv')
    df = df.sort("Orig IP Address")
    headers = ["InviteTime (Oracle)","Orig Number","Orig IP Address","Dest Number"]
    df.to_csv('output.csv', cols=headers, index=False)
    os.remove("c:\\python27\\work\\spoofing.csv")

1 个答案:

答案 0 :(得分:0)

替换功能不起作用吗?

def replace_ip(path,ip,name):
    fin = open(path)
    inserted = [i.replace(ip,ip+name) for i in fin.readlines()]
    fin.close()
    fout = open(path,"w")
    fout.write("\n".join(inserted))
    fout.close()
#example
#replace_ip("test.csv","1.2.3.4","COMPANYNAME")