Python CSV read row by row and insert new data
Question: I have a csv file, from which I will read row by row and for certain field the
data need to be processed and insert the results into another field in the
same row before moving on to the next field.

I tried various methods like:

    
    
    w = open('test.csv', 'w+')
    csv_r = csv_reader(w)
    csv_w = csv.writer(w)
    
    for row in csv_r:
        row[10] = results
        csv_w.writerows(row)
    

But I am getting blank. Is there any other way doing this?

Basically i need to read a specific element in a row and then process the data
and the result will be appended into another element in the same row.


Answer: `w+` empties/truncates your file so you have nothing to iterate over. It is
`r+` for reading and writing.

To update the file either store all the updated rows, reopen the file and
write or a much better approach is use a
[tempfile.NamedTemporaryFile](https://docs.python.org/2/library/tempfile.html#tempfile.NamedTemporaryFile)
to write to then replace the original with shutil.move.

    
    
    from tempfile import NamedTemporaryFile
    from shutil import move
    import csv
    
    
    with open("test.csv") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:   
        # write all updated rows to out tempfile
        csv_w = csv.writer(out)
        csv_r = csv.reader(f)
        for row in csv_r:
           row[10] = results
           csv_w.writerows(row)
    # replace original file with updated
    move(temp.name,"test.csv")
    

