Getting this error _csv.Error: sequence expected in Python
Question: I am trying to write a python script called header.py where I have a list of
headers which is:-

    
    
    header = ['name', 'age', 'gender']
    

I am trying to append a header to it and write it in a csv file.

Here is my code snippet:-

    
    
    import csv  
    header = ['name', 'age', 'gender']
    updated_csv_writer = csv.writer(open("updatedQueryOutput.csv", "w"),delimiter = ',')
    appendAdd = header.append("address")
    updated_csv_writer.writerow(appendAdd)
    

But I am getting this error:-

    
    
    _csv.Error: sequence expected
    

I don't know what is wrong with my code. Any help?Thanks


Answer: `append` mutates the list but doesn't return it, so you need to move the
header.append statement out onto its own. See this top-level example:

    
    
    Python 2.7.5+ (default, Feb 27 2014, 19:37:08) 
    [GCC 4.8.1] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> a = [1,2,3]
    >>> a.append(4)
    >>> a
    [1, 2, 3, 4]
    

So you could modify your code like this:

    
    
    import csv  
    header = ['name', 'age', 'gender']
    updated_csv_writer = csv.writer(open("updatedQueryOutput.csv", "w"),delimiter = ',')
    header.append("address")
    updated_csv_writer.writerow(header)
    

If you wanted to preserve the original value of `header`, you could always
make a new list like this:

    
    
    header_new = header + ['address']
    

