在Python中覆盖/更改CSV上的字段

2024-04-29 03:28:27 发布

您现在位置:Python中文网/ 问答频道 /正文

没有太多的Python(3.4)的经验,但我在一个程序,这将允许您添加牌照和编辑'状态'。这是一个停车场程序,所以状态是In/Out。你知道吗

我唯一的问题是,我不知道如何在输入之后编辑CSV文件上的特定字段。例:从里到外。你知道吗

例如CSV:

NH08OTR, 2008, Vauxhall, Corsa, Blue, In

我想能够将最后一个字段从'In'更改为'Out',但是CSV的行数是可变的,所以我只希望它在特定的车牌上执行。示例如下:

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

然后我希望它把CSV上的“In”改为out。你知道吗

希望你能理解,谢谢你的阅读。你知道吗


Tags: 文件csvtoin程序编辑状态status
2条回答

假设您有一个包含内容的文件plate_status.csv

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

等等。只要文件不是太大,我会先读入整个文件,然后更新和覆盖:

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

现在文件plate_status.csv读取:

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

给定csv:

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

我们要打开它,在内存中编辑它,然后保存编辑,因此:

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)

相关问题 更多 >