首页 > 解决方案 > 使用 Pandas 写入文件会创建空行

问题描述

我正在使用 pandas 库将 mysql 数据库的内容写入 csv 文件。

但是当我编写 CSV 时,每隔一行都是空白的:

csv中的空行

此外,它在左侧打印我不想要的行号。第一列应该是“帐号”。

这是我的代码:

destination = 'output_file.txt'
read_sql = """ SELECT LinkedAccountId,ProductName,ItemDescription,ResourceId,UnBlendedCost,UnBlendedRate,Name,Owner,Engagement FROM billing_info ;"""
fieldnames = ['Account Number', 'Product Name', 'Item Description', 'Resource ID', 'UnBlended Cost', 'UnBlended Rate', 'Name', 'Owner', 'Engagement']
# Open the file
f = open(destination, 'w')
cursor.execute(read_sql)
while True:
    # Read the data
    df = pd.DataFrame(cursor.fetchmany(1000))
    # We are done if there are no data
    if len(df) == 0:
        break
    # Let's write to the file
    else:
        df.to_csv(f, header=fieldnames)

为什么在数据行之间打印空白行?如何让它创建没有空行且左侧没有行号列的文件?

标签: pythonpandas

解决方案


查看 to_csv 的选项:https ://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html

为方便起见,我在这里发布了一些感兴趣的项目:

line_terminator : 字符串,可选

要在输出文件中使用的换行符或字符序列。默认为 os.linesep,这取决于调用此方法的操作系统('n' 用于 linux,'rn' 用于 Windows,即)。

index : 布尔值,默认为 True

写行名(索引)。

可能是您正在寻找的东西。至于空行,请尝试明确指定一个换行符:

df.to_csv(f, header=fieldnames, index=False, line_terminator='\n')

推荐阅读