首页 > 解决方案 > 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

有什么建议么?

标签: python

解决方案


您可以使用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])

推荐阅读