0

csv文件工作正常。也是如此,dictionary但我似乎无法检查csv文件中的值以确保我没有添加重复的条目。我怎样才能检查这个?我试过的代码如下:

    def write_csv():
        csvfile = csv.writer(open("address.csv", "a"))
        check = csv.reader(open("address.csv"))
        for item in address2:
            csvfile.writerow([address2[items]['address']['value'],address2[items]['address']['count'],items, datetime.datetime.now()])


    def check_csv():
        check = csv.reader(open("address.csv"))
        csvfile = csv.writer(open("address.csv", "a"))
        for stuff in address2:
            address = address2[str(stuff)]['address']['value']
            for sub in check:
                if sub[0] == address:
                    print "equals"
                    try:
                        address2[stuff]['delete'] = True
                    except:
                        address2[stuff]['delete'] = True
                else:
                    csvfile.writerow([address2[stuff]['address']['value'], address2[stuff]['address']['count'], stuff, datetime.datetime.now()])

有任何想法吗?

4

1 回答 1

1

您的 CSV 和 dict 结构有点不稳定 - 我很想知道它是否已设置,或者您是否可以将它们更改为更有用。这是一个基本上可以满足您需求的示例-您必须更改一些内容以适应您的格式。最重要的更改可能不是写入您正在阅读的文件 - 这会导致头痛。

这可以满足您对删除标志的要求 - 是否有外部需求?如果没有,几乎可以肯定有更好的方法(删除坏行,将好行保存在其他地方等 - 取决于你在做什么)。

无论如何,这是一个例子。我首先使用注释块来创建 csv 文件,然后将新地址添加到列表中并运行其余部分。它不是一遍又一遍地遍历文件,而是按地址进行查找字典并存储行号,然后如果在读取 csv 文件时找到它,它会使用它来更新删除标志。您需要取出打印件并取消注释最后一行以实际写入新行。

import csv, datetime

addresses = [
    {'address': {'value': '123 road', 'count': 1}, 'delete': False},
    {'address': {'value': '456 road', 'count': 1}, 'delete': False},
    {'address': {'value': '789 road', 'count': 1}, 'delete': False},

    {'address': {'value': '1 new road', 'count': 1}, 'delete': False},
]

now = datetime.datetime.now()

### create the csv
##with open('address.csv', 'wb') as csv_file:
##    writer = csv.writer(csv_file)
##    for row in addresses:
##        writer.writerow([ row['address']['value'], row['address']['count'], now.strftime('%Y-%m-%d %H:%M:%S') ])

# make lookup keys for the dict
address_lookup = {}
for i in range(len(addresses)):
    address_row = addresses[i]
    address_lookup[address_row['address']['value']] = i

# read csv once
with open('address.csv', 'rb') as csv_file:
    reader = csv.reader(csv_file)
    for row in reader:
        print row
        # if address is found in the dict, set delete flag to true
        if row[0] in address_lookup:
            print 'flagging address as old: %s' % row[0]
            addresses[ address_lookup[row[0]] ]['delete'] = True

with open('address.csv', 'ab') as csv_file:
    # go back through addresses and add any that shouldnt be deleted to the csv
    writer = csv.writer(csv_file)
    for address_row in addresses:
        if address_row['delete'] is False:
            print 'adding row: '
            print address_row
            #writer.writerow([  row['address']['value'], row['address']['count'], now.strftime('%Y-%m-%d %H:%M:%S') ])
于 2013-04-09T18:42:44.793 回答