How do I read and write to the same CSV file

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Mon Sep 10 11:01:32 EDT 2007


On Mon, 10 Sep 2007 07:27:46 -0700, Chris wrote:

> I want to update one field in a row for a csv file. So far my code looks
> something like this
> 
> cf_stream = open("\\config.csv","r+") 
> csv_file = csv.DictReader(cf_stream, ['Algorithm','LastModified'])
> 
> and then I know I can do something like this
> 
> for row in csv_file
>       name = row["Algorithm"]
>       date = row["LastModified"]
> 
> now what I want is something like this
> 
> if date == 0:
>       date = os.getmtime()
>       # now this is where I want to write into the row of the same csv
> file but only updating that one field
> 
> How can I do this?

With difficulty unless the bytes you are writing to are exactly the same 
length as the bytes that were there before.

In my opinion, unless you're writing a file with fixed-length fields, and 
maybe not even then, give up the dream of writing directly in place. 
Unless your file is HUGE, the chances are that trying to modify it in 
place is not only harder work but also slower.

But if you insist... you might be able to use cf_stream.seek() to move to 
the current position in the file, then write the bytes you want. How do 
you find the current position? Black magic or voodoo might help. 
Otherwise you might count every character of every line up to the field 
you want. Don't forget delimiters, quote marks and newlines. Good luck.



-- 
Steven.



More information about the Python-list mailing list