当我用csv编写时,如何在Python中分隔列

2024-10-01 19:32:29 发布

您现在位置: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正在读取表名 表的名称如下(string,ex:a000010) 我从这里收集表名。 然后,执行并得到结果。在

enter image description here

我的代码的实际输出是。。 enter image description here

我的期望是

enter image description here

(不是3列。。有2000张桌子)

我以为我的代码就快找到答案了。。。但它不起作用。。 我的工作快完成了,但我没能完成这部分。 我在谷歌上搜索了将近10个小时。。 我不知道怎么。。请帮忙

我觉得这部分有问题

^{pr2}$

Tags: csvinimportfordataresultopenconn
1条回答
网友
1楼 · 发布于 2024-10-01 19:32:29

^{}方法允许您在输出csv文件中编写一个。这意味着一旦您调用了writerow方法,该行就会被写入,您将无法返回该行。编写代码时:

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

你是说:

"For each result, write a line containing data_kp[i] then write a line containing row."

这样,所有内容都将以data_kp[i]和{}之间的交替书写。在

令人惊讶的是,这并不是我们从你们的实际产出中得到的。我觉得你改变了一些东西。像这样:

^{pr2}$

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

1。在一个单元格中获取表名,并且不拆分

首先,让我们看一下关于^{}的文档:

A row must be an iterable of strings or numbers for Writer objects

但是你的data_kp[i]String,而不是“iterable of String”。这不行!但你也没有出错,为什么?这是因为在python中,String本身可能被认为是String的iterable。你自己试试:

for char in "abcde":
    print(char)

现在,你可能已经明白了要做什么才能让事情运转起来:

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

现在您的表名只显示在1个单元格中!但我们还有一个问题。。。在

2。获取并排显示的表名

在这里,这是代码逻辑中的一个问题。你正在浏览你的表名,写下包含它们的行,并期望它们被并排书写,得到日期列!在

您的代码需要重新考虑一下,因为csvwriter不是用来写列而是用来写行的。然后我们将使用^{}模块的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)

注意: 这里提供的代码尚未测试,可能包含错误。不过,您应该能够(通过使用我提供的文档)来修复它,以便使其正常工作!祝你好运:)

相关问题 更多 >

    热门问题