使用 Pandas 写文件会产生空行 [英] Using Pandas to write file creates blank lines

查看:87
本文介绍了使用 Pandas 写文件会产生空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using the pandas library to write the contents of a mysql database to a csv file.

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

But when I write the CSV, every other line is blank:

此外,它在左侧打印了我不想要的行号.第一列应为帐号".

Also, it's printing line numbers to the left that I do not want. The first column should be 'Account Number'.

这是我的代码:

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)

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

Why is it printing blank lines between the lines with data? How can I get it to create the file without blank lines and without the line number column to the left?

推荐答案

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

Have a look at the options for to_csv: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html

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

For convenience, I have posted some items of interest here:

line_terminator : 字符串,可选

line_terminator : string, optional

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

The newline character or character sequence to use in the output file. Defaults to os.linesep, which depends on the OS in which this method is called (‘n’ for linux, ‘rn’ for Windows, i.e.).

index : bool,默认为 True

index : bool, default True

写行名称(索引).

可能就是您要找的东西.至于空行,请尝试明确指定一个换行符:

Are probably what you're looking for. As for the empty lines, try explicitly specifying a single newline:

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

这篇关于使用 Pandas 写文件会产生空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆