【发布时间】:2019-06-01 00:12:52
【问题描述】:
我正在使用 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)
为什么在数据行之间打印空白行?如何让它创建没有空行且左侧没有行号列的文件?
【问题讨论】:
-
尝试
index=False排除行标识符。 -
您运行的是什么操作系统? MS Windows 中的 Pandas to_csv() 似乎将 EOL 设置为 \r\r\n 提供额外的空白行