Skip to content Skip to sidebar Skip to footer

How To Write Back To Open Csv File In Python

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,

Solution 1:

You need to do it in two steps:

  1. Read the csv file and store information

    import csv
    
    withopen("propertyOutput.csv", "rbw") as fp:
        reader = csv.DictReader(fp, skipinitialspace=True)
        table= [rowforrowin reader]
        header = reader.fieldnames 
    
  2. Write the information to an new file or replace old file

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

Solution 2:

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).

Post a Comment for "How To Write Back To Open Csv File In Python"