Overwriting/changing a field on a CSV in Python
Question: Not got too much Python (3.4) experience however I'm working on a program
which will let you add number plates and edit the 'status'. It's a car parking
program so the status will be In/Out.

Only problem I have is that I don't know how to edit a specific field on a CSV
file following an input. Eg: From In to Out.

For example CSV:

    
    
    NH08OTR, 2008, Vauxhall, Corsa, Blue, In
    

I want to be able to change the last field from 'In' to 'Out' however the CSV
will have a variable amount of rows so I only want it to do it on a specific
registration plate. Example below:

    
    
    Please choose a number plate to change the status of: NH08OTR
    Status change: Out
    Status successfully changed to 'Out'
    

I then want it to change the 'In' on the CSV to out.

Hope you understand and thanks for reading.


Answer: Given a csv:

    
    
    NH08OTR, 2008, Vauxhall, Corsa, Blue, In
    NH08OTY, 2008, Vauxhall, Corsa, Blue, Out
    NH08OTZ, 2008, Vauxhall, Corsa, Blue, In
    

We want to open it, edit it in memory, then save the edit, hence:

    
    
    import csv
    
    # Open csv
    r = csv.reader(open('car_parking.csv')) 
    line_in = [k for k in r]
    
    #look for plate
    number_plate  = 'NH08OTZ'
    
    #get current parking status
    find_plate=([i for i,k in enumerate(line_in) if k[0] == number_plate]) #find plate in array
    current_park_status = line_in[find_plate[0]][5]
    
    print current_park_status
    
    #edit array position, with new status
    new_parking_status = 'IN'
    line_in[find_plate[0]][5] = new_parking_status
    
    #overwrite cv with new result 
    out = csv.writer(open('car_parking.csv', 'w'))
    out.writerows(line_in)
    

