如何用python写回打开的csv文件

2024-04-19 22:23:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我设法得到了csv数据并得到了城市和州,但我不知道如何将新数据写入最后一列。{a1}但不显示如何创建一个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

Tags: 文件csvtheto数据notcolumnthis
2条回答

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

因此,要更改CSV文件的内容,您必须重写它(好消息是,CSV模块使它非常容易)。在

您需要分两步来完成:

  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)
    

相关问题 更多 >