You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python脚本导出CSV时NULL值处理异常:末尾仅留尾随逗号

问题:导出CSV时NULL值仅留尾随逗号,需替换为''

我用Python 3执行数据库存储过程,将数据存入DataFrame后导出为.csv文件,代码能正常运行,但末尾字段为NULL时,仅留下一个尾随逗号。

我的脚本:

def GenerateCSV(fileName):

    connection_string = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=dev;DATABASE=Cities;UID=z;PWD=z"
    connection_url = URL.create(
        "mssql+pyodbc", query={"odbc_connect": connection_string})

    engine = sa.create_engine(connection_url)

    qry = text("EXECUTE dbo.sp_city_parser")
    with engine.connect() as con:
        rs = con.execute(qry)

    df = pd.read_sql_query(qry, engine)

    df.to_csv(fileName, encoding='utf-8', mode='a', index= False, header=False)

程序生成的.csv内容:

*CityName,*CityID,*CityCountryCode,*CitySize,CityPopulation
Tokyo,656,5,X-Large,
Chicago,887,9,Large,
Berlin,432,3,Large,

期望效果是用''表示NULL值,例如:

Tokyo,656,5,X-Large,'' 

解决方案

只需在to_csv方法中添加na_rep="''"参数,该参数会将DataFrame中的NaN/NULL值替换为指定字符串。同时可以去掉代码中多余的con.execute(qry),因为pd.read_sql_query会自行执行查询语句。

修改后的代码:

def GenerateCSV(fileName):

    connection_string = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=dev;DATABASE=Cities;UID=z;PWD=z"
    connection_url = URL.create(
        "mssql+pyodbc", query={"odbc_connect": connection_string})

    engine = sa.create_engine(connection_url)

    qry = text("EXECUTE dbo.sp_city_parser")

    df = pd.read_sql_query(qry, engine)

    df.to_csv(fileName, encoding='utf-8', mode='a', index=False, header=False, na_rep="''")

这样导出的CSV中,所有NULL值都会被替换为'',包括末尾字段的NULL,就能得到预期格式。


内容的提问来源于stack exchange,提问作者SkyeBoniwell

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 13:35:07