1

我可以让它输出我为安全起见已删除的 MYSQL 命令,但是当我尝试将此制表符分隔的输出写入 CSV 时,我一直收到错误消息。任何有助于提升 Python 新手的帮助将不胜感激。

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

1 回答 1

1

我敢打赌你得到的错误是:

TypeError:必须是字符串或缓冲区,而不是列表

contents是一个列表,你不能通过write(). 引用自文档

文件.write(str)

将字符串写入文件。

相反,使用csvwriter.writerows()

with open("/home/oatey/" + du + ".csv", "wb") as wd:
     cw = csv.writer(wd, quotechar='', quoting=csv.QUOTE_NONE)
     cw.writerows(contents)
于 2013-10-08T18:15:48.120 回答