2013-10-08 146 views
1

我能夠得到這個輸出我的MYSQL命令,我已經刪除了安全性,但是當我嘗試寫這個製表符分隔輸出到CSV時,我不斷收到錯誤。任何幫助提升Python新手,將不勝感激。製表符分隔到csv

#!/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) 
+2

什麼是錯誤您收到? –

+0

當你通過子進程執行你的命令時,可能會要求mysqldump爲你完成這項工作並導出爲CSV作爲選項嗎? 'mysqldump -u [username] -p -t -T/path [database] --fields-enclosed-by = \「--fields-terminated-by =,' – Majid

+0

通常情況下是...但這是一個自動化步驟的一部分,用戶輸入csv的路徑... – goat

回答

1

我敢打賭,你所得到的錯誤是:

TypeError: must be string or buffer, not list

contents是一個列表,你可以不通過write()寫一個清單。從docs報價:

file.write(str)

Write a string to the file.

相反,使用csvwriter.writerows()

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

我得到一個屬性錯誤:'模塊'對象沒有'作家'的屬性,我試着csv.writer和csvwriter .... – goat

+0

它的工作在我從目錄的title中刪除了csv文件後,導致模塊失敗! – goat