【问题标题】:Python convert a Tuple to CSV stringPython 将元组转换为 CSV 字符串
【发布时间】:2023-01-10 03:58:41
【问题描述】:

我正在尝试实现一个 REST api 以 CSV 格式从 SQL 数据库返回记录。我想使用 import csv 进行转换,我想使用发电机这样我就可以流式传输结果。

这是我试过的。

def get_data(query) -> Generator[str, None, None]:
    with pyodbc.connect(connStr) as conn:
        with conn.cursor() as cursor:
            cursor.execute(query)
            while 1:
                row = cursor.fetchone()
                if not row: break
                data = io.StringIO()
                csv.writer(data).writerow(row)
                yield data.getvalue()

这行得通,但我不喜欢它。它看起来太冗长了,它创建了很多临时的 StringIO 和 writer 对象!请告诉我一个更好的方法。

【问题讨论】:

    标签: python-3.x csv


    【解决方案1】:

    我想我可以使用 seek 重用 StringIO ...

    def get_data(query) -> Generator[str, None, None]:
        data = io.StringIO()
        writer = csv.writer(data)
        with pyodbc.connect(connStr) as conn:
            with conn.cursor() as cursor:
                cursor.execute(query)
                while 1:
                    row = cursor.fetchone()
                    if not row: break
                    data.seek(0)
                    writer.writerow(row)
                    yield data.getvalue()
    

    【讨论】:

      猜你喜欢
      • 2013-11-07
      • 2021-05-30
      • 1970-01-01
      • 2012-03-15
      • 2022-07-24
      • 2013-05-05
      • 1970-01-01
      • 2019-07-28
      • 2018-11-11
      相关资源
      最近更新 更多