[Tutor] help cvs module writerow issue

David Jamieson david.jamieson at gmail.com
Thu Aug 20 14:30:17 CEST 2009


Hi All,

I am looking to make an append to csv file function more dynamic by
allowing it to receive a variable number of arguments to write out to
a single a csv file row. The funtion is an append to file function
that writes out test date to a csv file. Reason for trying to make it
dynamic is to allow for future expansion of data capture during a test
run.
I have an issue when trying to format the output to the
csv.write(file).writerow() call to accept the variable number of
arguments as individual cell values when written to the csv file. I
have tried a few ways to escape the variable values but to no avail.
When I check the csv file it has the timestamp in one cell on the row
and the data in the second cell '1','2','3','4','5' Has this issue to
do with the output_str being a str type and the writerow not
interpreting it correctly. I added a number 2 to the writerow line to
prove that I can write to an individual cell

My code is below, sorry if the formatting goes awry.

function call
=========
append_to_file(output_file_name,'1','2','3','4','5')

file
==
output_file_name = 'C:\\rubbish.csv'

function def
========
def append_to_file(append_file_name,*values):
    #Open the test results file and append test data.
    output_str =' '
    file_out = open(append_file_name,'ab')
    #Creating a timestamp for the test results
    time = datetime.datetime.now()
    time_stamp = time.ctime()
    #Building a output str to follow the syntax required for writerow
'x','x','x'
    for x in values:
        output_str = output_str+"'"+x+"'"+","
    str_length = len(output_str)
    #removing the last , from the output_str variable
    output_str = output_str[0:(str_length-1)]
    print "The final output string is ",output_str
    print "The output string is of type ",type(output_str)
    #list(output_str)
    csv.writer(file_out).writerow([time_stamp, output_str]+['2'])
    #Close the file
    file_out.close()
--
Cheers David and thanks in advance of any help given.



-- 
Cheers David.


More information about the Tutor mailing list