python - Python:在 CSV 文件中写入变量的值
问题描述
我正在尝试将一些变量(sql 查询值)写入 csv 文件,以“|”分隔 如下:
with open(f'/c/doc/output/testfile.csv', 'w') as outcsv:
writer = csv.writer(outcsv)
cursor.execute(sqlscript)
for row in cursor:
p_date = row['t_date']
p_order = row['t_order']
results = ("|".join([f"{p_date}"+ f"{p_order}"]))
writer.writerow(results)
但结果被 ',' 分割:2,0,2,0,-,0,4,-,0,3,A,A,0,0,1
有什么建议么?
解决方案
您可以使用delimiter
可选参数来指定新的分隔符。默认delimiter
值为逗号,因此您必须将新分隔符指定为|
.
采用:
with open(f'your_csv_file_path', 'w') as outcsv:
writer = csv.writer(outcsv, delimiter="|")
cursor.execute(sqlscript)
for row in cursor:
p_date = row['t_date']
p_order = row['t_order']
writer.writerow([p_date, p_order])
推荐阅读
- scala - 如何在 Scala Spark 项目中使用 PySpark UDF?
- php - 使用 PHP 从亚马逊 MWS API 获取订单数据
- vim - 用于方案的 Vim 8.0 扩展语法高亮
- ag-grid - 在没有企业许可证的情况下在 ag-grid 中实施 Master 详细信息
- c++ - 为什么 push_back 和 emplace_back 结合在一起时会有不同的行为
- css - 顶部菜单问题的间距
- c - Pairing even and odd numbers in an array
- ios - 图像未在方向更改时调整大小
- angular - 角度测试:FormControl valueChanges Observable
- mysql - 如何使用另一列作为乘数而不是行数 MySQL 从表中获取最高出现值