1

I created a csv function that should ask for a file path and for X number of strings to write to the file with an specified csv delimiter.

def WRITE_csv(csv_path,*args):
    with open(csv_path, "ab") as f:
        csv_list=csv.writer(f,delimiter='|')

        csv_string=""
        for arg in args:
            csv_string=csv_string+","+arg

        csv_string=csv_string[1:]

        csv_list.writerow([csv_string])

The problem is that the csv module is writing , instead of |


As a bonnus, I wanted to replace:

        csv_string=""
        for arg in args:
            csv_string=csv_string+","+arg

With a one-line function

csv_string="".format(','.join(arg for arg in args))

but it always giving me an empty string!

6
  • @Jongware: yet the delimiter argument lets you specify your own delimiter. Provided you actually use more than one column... Commented Aug 1, 2014 at 17:12
  • @Jongware This is why we can specify a delimiter.. Commented Aug 1, 2014 at 17:13
  • @rsm: but why are you then joining the args into a single string with commas? You appear to misunderstand how the writer works, you pass in a sequence of columns, not one string. Commented Aug 1, 2014 at 17:14
  • @Martijn Pieters i was wrinting a single string with commas because i noticed that when i write using writerow, i have to use the following format csv_list.writerow([string1,string2,string3,ect..]) Commented Aug 1, 2014 at 17:17
  • 1
    that's because you are then building a new list object. The , commas are not string values, they are Python syntax to delimit the different elements that you are asking Python to put into the list. Commented Aug 1, 2014 at 17:22

1 Answer 1

3

You are confusing the literal , string in your value for the delimiter. You are writing just one column:

csv_list.writerow([csv_string])

so the csv.writer() never has cause to put the | delimiter in, as there is no second column to delimit. You passed in one whole string, csv_string, as a one-value list, so naturally that is seen as the only column. The module does not split the string on commas again.

Leave putting in the delimiter to the writer instead:

def WRITE_csv(csv_path, *args):
    with open(csv_path, "ab") as f:
        csv_list=csv.writer(f,delimiter='|')    
        csv_list.writerow(args)

In other words, args is already the right type for the csv.writerow() call, you don't need to convert it here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.