如何让python在csv文件中搜索字典中的项目然后打印出整个excel行...谢谢

时间:2014-05-12 15:30:50

标签: excel csv python-3.x dictionary report

尝试让python在csv文件中搜索字典中的特定电话号码,然后返回整个excel行。谢谢。

示例代码:

import csv

def generateKnownReport(mypath, GKR):
    if GKR==True:
        with open("fileName.csv") as f:
            reader = csv.reader(f, delimiter=',')  
            file_one = list(reader)
        affiliate_phone_dict = {"xxx-xxx-xxxx":"Name 1","yyy-yyy-yyyy":"Name 2"}
        federal_phone_dict = {}
        for row in file_one:
            for each in row:
                search(affiliate_phone_dict,each)

def search(myDict, lookup):
    with open('KnownReport.csv','w') as f:
        for key, value in myDict.items():
            for value in key, value:
                if lookup in key:
                    f.write('{0}\n'.format(value))
                    f.write('{0}\n'.format(lookup))
     return 




GKR=True
mypath="November2013 T-Mobile Statement - Daily Detail.csv"
generateKnownReport(mypath, GKR)

为了清楚,我试图让python将CSV文件的整行写入输出文件而不仅仅是它正在搜索的内容。例如,如果我在这个csv文件中搜索:

Date        Time Length Cost   Bill Category                                      Destination Number Destination City Origin Number Origin City Type

01/01/0001  10:37   3   $0.00   LOCAL AIRTIME, LONG DISTANCE and INTERNATIONAL CHARGES  xxx-xxx-xxxx    City Name   aaa-aaa-aaaa    City Name   Mobile

01/01/0001  10:37   10  $0.00   LOCAL AIRTIME, LONG DISTANCE and INTERNATIONAL CHARGES  yyy-yyy-yyyy    City Name   zzz-zzz-zzzz    City Name   Mobile

对于数字xxx-xxx-xxxx和yyy-yyy-yyyy,我想要一行代码打印出找到这些数字的整行。谢谢。

1 个答案:

答案 0 :(得分:0)

我不太确定你在问什么,但是如果你想打印包含affiliate_phone_dict中任何数字的每一行,这样做:

lookup = {'name1': 'xxx-xxx-xxxx',
          'name2': 'yyy-yyy-yyyy'}

with open('data.csv') as data_file, open('out.csv', 'w') as out_file:
    for row in data_file:
        if any(num in row for num in lookup.values()):
            out_file.write(row)

<强> data.csv

Date Time Length Cost Bill Category Destination Number Destination City Origin Number OriginCity
01/01/0001  10:37   3   $0.00   LOCAL AIRTIME, LONG DISTANCE and INTERNATIONAL CHARGES  xxx-xxx-xxxx    City Name   aaa-aaa-aaaa    City Name   Mobile
01/01/0001  10:37   10  $0.00   LOCAL AIRTIME, LONG DISTANCE and INTERNATIONAL CHARGES  yyy-yyy-yyyy    City Name   zzz-zzz-zzzz    City Name   Mobile
01/01/0001  10:37   10  $0.00   LOCAL AIRTIME, LONG DISTANCE and INTERNATIONAL CHARGES  123-456-7890    City Name   zzz-zzz-zzzz    City Name   Mobile

<强> out.csv

01/01/0001  10:37   3   $0.00   LOCAL AIRTIME, LONG DISTANCE and INTERNATIONAL CHARGES  xxx-xxx-xxxx    City Name   aaa-aaa-aaaa    City Name   Mobile
01/01/0001  10:37   10  $0.00   LOCAL AIRTIME, LONG DISTANCE and INTERNATIONAL CHARGES  yyy-yyy-yyyy    City Name   zzz-zzz-zzzz    City Name   Mobile