如何回写在python中打开csv文件

时间:2013-12-02 19:40:46

标签: python csv

我正在尝试浏览csv文件,验证邮政编码并将城市和州写入csv文件的最后一列。

我设法获取csv数据并获取城市和州,但我不明白如何将新数据写入最后一列。像this这样的示例显示了如何创建csv,但不能使用现有的csv。

到目前为止,这是我的代码:

with open("propertyOutput.csv", "rbw") as fp:
    reader = csv.DictReader(fp, skipinitialspace=True)
    table = [row for row in reader]
    for rows in table:
        stringNeed = rows['zip']
        if not stringNeed.isdigit(): 
            print"not number"  #would like to write this to the column
            pass
        else:
            if not len(stringNeed) == 5:  
                print"string not 5 long"  # would like to write this to the column
            else:
                x = getCityState(stringNeed)
                print x  # would like to write this to the column

2 个答案:

答案 0 :(得分:3)

您需要分两步完成:

  1. 阅读csv文件并存储信息

    import csv
    
    with open("propertyOutput.csv", "rbw") as fp:
        reader = csv.DictReader(fp, skipinitialspace=True)
        table = [row for row in reader]
        header = reader.fieldnames 
    
  2. 将信息写入新文件或替换旧文件

    with open("propertyOutput.csv", "wb") as fp:
        writer = csv.DictWriter(fp, header)
        for row in table:
            if not stringNeed.isdigit(): 
                rows['zip'] = "not number"
            # even more stuff to check and edit here
            # write the edited row
            writer.writerow(row)
    

答案 1 :(得分:0)

通常,文件不支持“插入”的概念。你只能删除它们,覆盖它们(也就是说,要么完全替换文件,要么用完全相同数量的(不同)字节替换一定数量的字节),或者附加它们。

因此,要更改CSV文件的内容,您必须覆盖它(好消息是,CSV模块使其变得非常简单)。