简体   繁体   中英

Overwriting/changing a field on a CSV in Python

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.

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)

Let's assume you have a file plate_status.csv with contents

""" 
NH08OTR, 2008, Vauxhall, Corsa, Blue, In
NH0873R, 2004, Vauxhall, Corsa, Red, Out
...
"""

etc. As long as the file isn't too large, I would read in the whole file first, then update and overwrite:

import csv

def update_status( filename, plate, status ):
    # read and update
    with open( filename) as f:
        reader = csv.reader( f, delimiter=',' )
        line_dict = dict([ ( x[0].strip() , map(lambda y:y.strip() ,x[1:])) for x in reader] )
        line_dict[ plate ][-1] = status

    # save new
    with open( 'plate_status.txt', 'w') as f:
        writer = csv.writer(f )
        new_file_rows = map( lambda x : [ x[0] ]+ x[1], line_dict.iteritems() )
        writer.writerows( new_file_rows )            

update_status( 'plate_status.csv', 'NH08OTR', 'Out' )

Now the file plate_status.csv reads:

""" 
NH08OTR, 2008, Vauxhall, Corsa, Blue, Out
NH0873R, 2004, Vauxhall, Corsa, Red, Out
...
"""

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM