> 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
>You seem to misunderstand writerow(). You don't have to escape the >values yourself, the csv module will do that. > 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)] >You could write this more simply as >output_str = ','.join("'"+x+"'" for x in values) >but see below for what you really want. > 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']) >Here you are saying that you want to write a row with three elements - >the time stamp, the string you constructed in output_str, and the >string '2'. That's not really what you want - you want each value in a >separate cell. Skip all the output_str stuff and just >csv.writer(file_out).wrinerow([time_stamp] + list(values) + ['2']) >Kent Hi Kent, thank you for your help in sorting out my writerow issue and for the better way to join strings. I have the code applied to my project. Cheers David. _______________________________________________ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor