tab delimited to csv
Question: I am able to get this to output my MYSQL command which I have removed for
security, however I keep getting an error when I try and write this tab
delimited output to a CSV. Any help to boost the Python rookie would be
appreciated.

    
    
    #!/usr/bin/pytho
    import sys, csv
    import MySQLdb
    import os
    import mysql.connector
    import subprocess
    import string
     if __name__ == '__main__':
    
    du = sys.argv[1]
    csv_home = '/home/oatey/bundle_' + du + '.csv'
    input = sys.stdin
    output = sys.stdout
    
    
    #read and rewrite to file with arguement
    new = open("/home/oatey/valid.sql2", "w")    
    with open("/home/oatey/bundle.sql")as write_query:
    #read_file = write_query.read()
    
         for line in write_query:
         lr = line.replace('{$$}', du)
         print lr
         new.write(lr)
         new.close()
         write_query.close()         
    with open("/home/oatey/valid.sql2") as w:
         mysql_output = subprocess.check_output(MYSQL_COMMAND, stdin=w)    
    
         #print mysql_output
         b = open("/home/oatey/" + du + ".txt", "r+")
        #",".join("%s" % i for i in mysql_output
         b.write(mysql_output)
         print mysql_output        
    b.close()
    
    #read tab-delimited file
    with open("/home/oatey/" + du + ".txt", 'rb') as data:    
         cr = data.readlines()
         contents = [line for line in cr]
    
    with open("/home/oatey/" + du + ".csv", "wb") as wd:
         cw = csv.writer(wd, quotechar='', quoting=csv.QUOTE_NONE)
         wd.write(contents)
    


Answer: I bet the error you are getting is:

> TypeError: must be string or buffer, not list

`contents` is a list, you cannot write a list via `write()`. Quote from
[docs](http://docs.python.org/2/library/stdtypes.html#file.write):

> file.write(str)
>
> Write a string to the file.

Instead, use
[csvwriter.writerows()](http://docs.python.org/2/library/csv.html#csv.csvwriter.writerows):

    
    
    with open("/home/oatey/" + du + ".csv", "wb") as wd:
         cw = csv.writer(wd, quotechar='', quoting=csv.QUOTE_NONE)
         cw.writerows(contents)
    

