2017-02-16 39 views
0
分隔列

我的代码是当我CSV写我如何在Python

import pymysql 
conn=pymysql.connect(host=.................) 
curs=conn.cursor() 
import csv 
f=open('./kospilist.csv','r') 
data=f.readlines() 
data_kp=[] 
for i in data: 
    data_kp.append(i[:-1]) 


c = csv.writer(open("./test_b.csv","wb")) 

def exportFunc(): 
    result=[] 
    for i in range(0,len(data_kp)): 
     xp="select date from " + data_kp[i] + " where price is null" 
     curs.execute(xp) 
     result= curs.fetchall() 

     for row in result: 
      c.writerow(data_kp[i]) 
      c.writerow(row) 

     c.writerow('\n') 



exportFunc() 

data_kp正在读表命名 表的名字都是这样(字符串,例如:a000010) 我收集表来自这里的名字。 然后,执行并得到结果。

enter image description here

我的代码的实际产量.. enter image description here

我的期望是

enter image description here

(不是3列。有2000台)

我以为我的代码接近答案......但它不工作ing .. 我的工作快完成了,但我无法完成这部分。 我几乎10小时一派.. 我不知道该怎么..请帮助

我觉得有什么不对这些部分

for row in result: 
      c.writerow(data_kp[i]) 
      c.writerow(row) 
+0

你能提供一个csv行的例子吗? –

+3

请显示输入,预期输出和实际输出(如csv,不是屏幕截图!)。 – hop

+0

我加入的exaple行 – JsYun

回答

0

csvwriter.writerow方法允许你写一个在您的输出csv文件中。这意味着,一旦你调用了writerow方法,该行就会被写入,而你不能回到它。当你写代码:

for row in result: 
    c.writerow(data_kp[i]) 
    c.writerow(row) 

你是在说:

“对于每个结果,编写包含data_kp[i]然后写一个包含row一个 线路的线路。”

这样,一切都将verticaly与交替data_kp[i]row之间写道。

令人惊讶的是,这不是我们在实际输出中得到的结果。我认为你已经改变了一些东西。类似的东西:

c.writerow(data_kp[i]) 
for row in result: 
    c.writerow(row) 

但是,这并不能完全解决您的问题,很明显:该表的名称显示不正确(每列一个字符)和他们没有并排侧。所以你在这里有两个问题:

1。在一个单元获取表的名称,而不是分裂

首先,让我们来看看关于csvwriter文档:

行必须是字符串或数字为作家的迭代对象

但是您的data_kp[i]String,而不是“String的迭代”。这不可行!但是你也没有得到任何错误,为什么?这是因为python中的String本身可能被认为是String的迭代。试图通过自己:

for char in "abcde": 
    print(char) 

而现在,你可能已经明白怎么做才能使事情的工作要做:

# Give an Iterable containing only data_kp[i] 
c.writerow([data_kp[i]]) 

您现在的表名显示在只有1个细胞!但是,我们还是有其他问题?

2.侧获取表格名称显示侧

在这里,它是在你的代码的逻辑存在问题。你正在浏览你的表名,写出包含它们的行,并期望它们并排写入并获得日期列!

您的代码需要一点反思,因为csvwriter不是用来写列而是用线。然后我们将使用itertools模块的zip_longest功能。有人可能会问为什么我不使用Python的内置函数zip:这是因为列的大小并不相同,并且zip函数一旦到达最短列表的末尾就会停止!

import itertools 

c = csv.writer(open("./test_b.csv","wb")) 

# each entry of this list will contain a column for your csv file 
data_columns = [] 

def exportFunc(): 
    result=[] 
    for i in range(0,len(data_kp)): 
     xp="select date from " + data_kp[i] + " where price is null" 
     curs.execute(xp) 
     result= curs.fetchall() 

     # each column starts with the name of the table 
     data_columns.append([data_kp[i]] + list(result)) 

    # the * operator explode the list into arguments for the zip function 
    ziped_columns = itertools.zip_longest(*data_columns, fillvalue=" ") 

    csvwriter.writerows(ziped_columns) 

注: 这里提供的代码没有经过测试,并可能包含错误。尽管如此,你应该能够(通过使用我提供的文档)来修复它,以使其工作!祝你好运:)