在Python2.7中编写CSV文件时,将列转换为文本或带撇号的前缀

2024-09-25 04:27:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,它通过pythonscsv writer将数据从数据库转储到CSV文件中(更准确地说,unicodesv)

我的问题是,我有一个列需要转换为文本或前缀作为撇号,因为它是一个16位数字,格式在Excel中查看时是科学的。否则,代码完全可以工作。列名简单地称为“value”。有什么干净的方法可以达到这个目的吗?在

def dump(self, sql, filename, include_headers=True):
    f = unicodecsv.writer(file(filename + ".csv", 'wb'), dialect=unicodecsv.excel, quoting=unicodecsv.QUOTE_ALL)
cnxn = pyodbc.connect(self.connect_string)
c = cnxn.cursor()
c.execute(sql)

if include_headers:
    f.writerow([d[0] for d in c.description])

    for row in c.fetchall():
        f.writerow(row)

   # f.close()
    cnxn.close()

Tags: inself脚本forclosesqlincludeconnect
1条回答
网友
1楼 · 发布于 2024-09-25 04:27:10

迭代行并将值替换为字符串:

第一个示例:定义一个进行更改的函数,然后使用map来实现更改:

import functools
def change(row, col):
    '''changes the column of a pyodbc row

    returns modified pyodbc row
    '''
    return setattr(row, col, str(getattr(row, col)))

# partial function that specifies the 'foo' column
change_foo = functools.partial(change, col = 'foo')

if include_headers:
    f.writerow([d[0] for d in c.description])
    rows = c.fetchall()
    # modify the column in each row
    rows = map(change_foo, rows)
    for row in rows:
        f.writerow(row)

第二个例子:只需在编写列之前修改它

^{pr2}$

甚至:

if include_headers:
    f.writerow([d[0] for d in c.description])
    for row in = c.fetchall():
        f.writerow(change_foo(row))

相关问题 更多 >