python:解码列表并将行写入csv

时间:2015-03-25 22:04:19

标签: python-3.x export-to-csv

尝试将sql查询写入csv但输出看起来像是编码的。当我尝试解码列表时抛出错误。我输入csv文件的输出如下:

Visit ID    Source  Vid 1   Vid 2   Vid 3   Vid 4   Vid 5
['']                        
|[-9223368141428696960   u'O\x00&\x00O\x00'  u'E\x00n\x00t\x00e\x00r\x00t\x00a\x00i\x00n\x00m\x00e\x00n\x00t\x00']| 



from pandas import *
import pandas.io.sql as psql
import sqlite3
import pyodbc
import csv
import codecs
with open('vidPathingTest.csv', 'wb') as csvfile:
        spamwriter = csv.writer(csvfile, delimiter=',',
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
    spamwriter.writerow(['Visit ID','Source','Vid 1','Vid 2','Vid 3','Vid 4','Vid 5'])

    cstr = 'XX;SERVER=XX;UID=XX;PWD=XX;DATABASE=;Threading=1'
    cnxn = pyodbc.connect(cstr)
    cursor = cnxn.cursor()

    command = '''sql query'''



    df = psql.read_sql(command, cnxn)
    output_row = [""]

    for index, row in df.iterrows():

        prevID = row[0]
        source = row[1]
        vid = row[2]

        if index is 0:
            output_row.append(prevID, source, vid)
            continue
        else:
            prevID = output_row[0]

        if prevID is row[0]:
            output_row.append(vid)
        else:
            spamwriter.writerow([output_row[a].decode('utf-16-le') for a in output_row])
            output_row = [""]
            prevID = row[0]
            output_row = [prevID, source, vid]

    cnxn.close()

1 个答案:

答案 0 :(得分:0)

字符串中有空字节,可以拆分,重新加入和写入:

spamwriter.writerow(["".join(a.split("\x00")) for a in output_row])

或者简单地替换:

 spamwriter.writerow([a.replace("\x00","") for a in output_row])