Writing Log CSV (Efficiently)
Tim Golden
mail at timgolden.me.uk
Mon Apr 16 11:10:48 EDT 2007
Robert Rawlins - Think Blue wrote:
> Thanks for that Tim,
>
> I could use a little more help with this CSV stuff this afternoon and I
> can't get it to write the output I want for the life of me. I'm trying to
> write a method for my logging class that receives a string as an argument,
> and then writes a row to the CSV with the string and a date/time stamp.
>
> ''' Add Application Log Entry '''
> def addApp(self, event):
> writer = csv.writer(open("some.csv", "a"))
> writer.writerow(event)
>
> Now if I do something like this; addApp('Application Started') then it
> writes to the CSV file somthing like.
>
> A,p,p,l,i,c,a,t,i,o,n, ,S,t,a,r,t,e,d
>
> Which isn't much use to me :-D any ideas how I can get something like this:
>
> 2007-01-01,13:00:00,Application Started
The writer.writerow method expects an iterable of some
sort. Usually you give it a list or a tuple (perhaps of
length one). You've given it a string, which it can happily
iterate over. Try:
for c in "Application Started":
print c
If you just want to print the string, pass it in as the
only element of a list or tuple:
writer.writerow ([event])
If you want to add a timestamp or whatever, then make a
list/tuple of both. (Tries to avoid restarting The Great
Tuple War (tm)):
import datetime
.
.
.
now = datetime.datetime.now ()
writer.writerow ([event, str (now)])
TJG
More information about the Python-list
mailing list