1

I'm trying to go through a csv file, validate zip codes and write the city and state to the last column in the csv file.

I managed to get the csv data and get the city and state, but I don't understand how to write the new data to the last column. SO examples like this show how to create a csv, but not work with an existing csv.

here is my code so far:

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
Community
  • 1
  • 1
DBWeinstein
  • 8,605
  • 31
  • 73
  • 118
  • I guess it is better to write everything in new file with added info than editing the open file. and I don't think their is any way to insert in the middle except rewrite whole file. – Ananta Dec 02 '13 at 19:45

2 Answers2

4

You need to do it in two steps:

  1. Read the csv file and store information

    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. Write the information to an new file or replace old file

    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)
    
user1251007
  • 15,891
  • 14
  • 50
  • 76
0

Files, in general, do not support the concept of "insertion". You can only delete them, overwrite them (that is, either replace the file entirely, or replace a certain number of bytes with exactly the same number of (different) bytes), or append to them.

So to change the contents of a CSV file, you will have to overwrite it (the good news is, the CSV module makes it pretty easy).

Max Noel
  • 8,810
  • 1
  • 27
  • 35