写入csv文件

时间:2012-12-06 23:55:45

标签: python csv file-io dictionary

假设我有一本字典:

dict = {'R150': 'PN000123', 'R331': 'PN000873', 'C774': 'PN000064', 'L7896': 'PN000447', 'R0640': 'PN000878', 'R454': 'PN000333'}.

我需要填写此示例csv文件:https://www.dropbox.com/s/c95mlitjrvyppef/sheet.csv

示例行

HEADER,ID,ReferenceID,Value,Location X-Coordinate,Location Y-Coordinate,ROOM,ALT_SYMBOLS,Voltage,Thermal_Rating,Tolerance,PartNumber,MPN,Description,Part_Type,PCB Footprint,SPLIT_INST,SWAP_INFO,GROUP,Comments,Wattage,Tol,Population Notes,Gender,ICA_MFR_NAME,ICA_PARTNUM,Order#,CLASS,INSTALLED,TN,RATING,OriginalSymbolOrigin,Rated_Current,Manufacturer 2,Status,Need To Mirror/Rotate Pin Display Properties,TOLERANCE,LEVEL
,,R150,1,,,,,<null>,<null>,<null>,,,to be linked,Resistor,TODO,<null>,<null>,<null>,<null>,1/16W,?,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>
,,R4737,1,,,,,<null>,<null>,<null>,,,to be linked,Resistor,TODO,<null>,<null>,<null>,<null>,1/16W,?,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>
,,R4738,1,,,,,<null>,<null>,<null>,,,to be linked,Resistor,TODO,<null>,<null>,<null>,<null>,1/16W,?,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>,<null>

具体来说,我需要根据我创建的dict的键填写PartNumber列。所以我需要遍历列ReferenceID并将该值与dict中的键进行比较。如果有匹配,我需要用该值填写相应的PartNumber单元格(在dict中)....

如果这一切都令人困惑我很抱歉我是python的新手并且遇到了csv模块的问题。

1 个答案:

答案 0 :(得分:0)

为了帮助您入门 - 这是使用csv.DictReader对象的内容,并循环浏览您的文件,一次一行,以及your_dict中基于行的ReferenceID存在的内容将PartNumber设置为该值,否则设置为空字符串。

如果您将此与http://docs.python.org/2/library/stdtypes.html#typesmappinghttp://docs.python.org/2/library/csv.html处的文档结合使用 - 您应该能够写出数据并更好地了解正在发生的事情。

import csv

your_dict = {'R150': 'PN000123', 'R331': 'PN000873', 'C774': 'PN000064', 'L7896': 'PN000447', 'R0640': 'PN000878', 'R454': 'PN000333'}
with open('your_csv_file.csv') as fin:
    csvin = csv.DictReader(fin)
    for row in csvin:
        row['PartNumber'] = your_dict.get(row['ReferenceID'], '')
        print row