擅长:python、mysql、java
<p>假设您有一个包含内容的文件<code>plate_status.csv</code></p>
<pre><code>"""
NH08OTR, 2008, Vauxhall, Corsa, Blue, In
NH0873R, 2004, Vauxhall, Corsa, Red, Out
...
"""
</code></pre>
<p>等等。只要文件不是太大,我会先读入整个文件,然后更新和覆盖:</p>
<pre><code>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' )
</code></pre>
<p>现在文件<code>plate_status.csv</code>读取:</p>
<pre><code>"""
NH08OTR, 2008, Vauxhall, Corsa, Blue, Out
NH0873R, 2004, Vauxhall, Corsa, Red, Out
...
"""
</code></pre>