嵌套的DictReaders没有重置

时间:2014-09-16 14:26:52

标签: python csv python-3.x

我已经嵌套了DictReader迭代器,但是我注意到for build in building中的for row in location在每次迭代后都没有重置import csv building = csv.DictReader(open('tblBuilding.csv', newline=''), delimiter=',', quotechar='"') purpose = csv.DictReader(open('tblPurpose.csv', newline=''), delimiter=',', quotechar='"') room = csv.DictReader(open('tblRoom.csv', newline=''), delimiter=',', quotechar='"') location = csv.DictReader(open('Locations.csv', newline=''), delimiter=',', quotechar='"') data, i = {}, 0 for row in location: result = {} for build in building: if row['Build'] == build['BuildingName']: result['BuildingID'] = build['BuildingID'] ,导致它只在第一次迭代后将它与构建中的最后一个对象进行比较。为什么不重置?

{{1}}

1 个答案:

答案 0 :(得分:2)

它们不会重置,因为底层文件对象未重置。您可以将文件重新回到开头,但考虑到第一行是标题行,所以也跳过它:

building_file = open('tblBuilding.csv', newline='')
building = csv.DictReader(building_file, delimiter=',', quotechar='"')


for row in location:
    result = {}
    for build in building:
        if row['Build'] == build['BuildingName']:
            result['BuildingID'] = build['BuildingID']
    building_file.seek(0)  # rewind the underlying file object to the start again
    next(building)  # skip header row

然而,您不应该首先在上嵌套嵌套的CSV文件。在处理位置之前,将建筑信息存储在字典中

with open('tblBuilding.csv', newline='') as building_file:
    building = csv.DictReader(building_file, delimiter=',', quotechar='"')
    buildings = {b['BuildingName']: b['BuildingID'] for b in building}

buildings词典现在将BuildingName映射到BuildingID值。现在,您可以在O(1)常数时间内查找建筑物,而不必遍历每个位置的所有CSV行

for row in location:
    result = {}
    building_id = buildings.get(row['Build'])
    if building_id:
        result['BuildingID'] = building_id