python - 使用 Pandas 写入文件会创建空行
问题描述
我正在使用 pandas 库将 mysql 数据库的内容写入 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)
为什么在数据行之间打印空白行?如何让它创建没有空行且左侧没有行号列的文件?
解决方案
查看 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')
推荐阅读
- vb.net - VB writeline 将损坏的行写入文本文件
- c# - 使用 C# 读取 XML 文件属性和元素
- java - 是否可以在 BufferedImage 中的其他像素之上不透明地绘制一条半透明颜色的线?
- laravel - 当服务器在 https 上运行时,url() 返回 http
- imap - 使用 OAuth2 以非交互方式通过后端服务连接到 Office365(栏初始设置)
- c++ - 错误:没有匹配函数调用 'std::vector
::erase(size_t&)' - ios - 如何从屏幕底部弹出 tableView?
- javascript - 如何在js折线图中获取两个输出JSON对象?
- d3.js - d3js v5:使用 JSON 文件中的组创建 SVG
- php - json_encode 不适用于嵌套数组