Python: write variables' values in CSV file

FedericoSala :

I'm trying to write some variables (sql query values) into a csv file, delimited by "|" as below:

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)

but the results are splitted by ',' : 2,0,2,0,-,0,4,-,0,3,A,A,0,0,1

any suggestions?

Shubham Sharma :

You can use the delimiter optional parameter to specify the new delimiter. The default delimiter is comma so you have to specify the new delimiter as |.

Use:

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])

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398297&siteId=1