我正在使用 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)
Run Code Online (Sandbox Code Playgroud)
为什么在带有数据的行之间打印空行?如何让它创建没有空行且左侧没有行号列的文件?
Alg*_*thm 23
看看 to_csv 的选项:https ://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_csv.html
为方便起见,我在这里发布了一些感兴趣的项目:
line_terminator : 字符串,可选
要在输出文件中使用的换行符或字符序列。默认为 os.linesep,这取决于调用此方法的操作系统('n' 代表 linux,'rn' 代表 Windows,即)。
和
索引:布尔值,默认为真
写行名称(索引)。
可能就是你要找的。至于空行,请尝试明确指定一个换行符:
df.to_csv(f, header=fieldnames, index=False, line_terminator='\n')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10751 次 |
| 最近记录: |