0

I spent all day trying to find a solution for this problem and as I didn't find one yet I'm coming here for you help!

I'm writing a CSV file exporter on python and I can't get it to output exactly how I want it to

let's say I have a list of strings containing several tutorial titles:

    tutorials = ['tut1', 'tut2, 'tut3']

and I want to print in the csv file's first line like this:

    First Name, Surname, StudentID, tut1, tut2, tut3

Now, this is the code I wrote to do so:

    tutStr= ' '
    for i tutorials:
          tutStr += i + ', '
    tutStr = tutStr[0:-3]

    with open('CSVexport.csv', 'wb') as csvFile:
            writer = csv.writer(csvFile, delimiter=',', quoting=csv.QUOTE_NONE)
            writer.writerow(['First Name'+'Surname'+'ID number'+tutStr)

This gives me the error:
"writer.writerow(['First Name'+'Surname'+'ID number'+labString]) Error: need to escape, but no escapechar set"

now, I know that the error has to do with csv.QUOTE_NONE and that I have to set an escapechar but I really don't understand how am I supposed to do so.

if I try without the QUOTE_NONE it'll automaticalle set the quotechar to ' " ' which will give me this output

    "First Name, Surname, StudentID, tut1, tut2, tut3"   --> don't want quotation marks!!!

Any idea?

0

1 Answer 1

1

If you are going to write something with writerow you need to pass a list there, not a list containing one big string separated by commas (it will appear as a string in one cell). quoting=csv.QUOTE_MINIMAL would help to quote strings that need to be quoted.

tutorials = ['tut1', 'tut2', 'tut3']
headers = ['First Name', 'Surname', 'ID number'] + tutorials
first_line = True
with open('CSVexport.csv', 'w') as csvFile:
        writer = csv.writer(csvFile, delimiter=',', quoting=csv.QUOTE_MINIMAL)
        if first_line:
           writer.writerow(headers)
           first_line = False
Sign up to request clarification or add additional context in comments.

1 Comment

For Python2: "If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference." For Python3: "If csvfile is a file object, it should be opened with newline=''".

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.