-2

I have data in this format, which is stored in a csv file: 3;6/3/2021;B;12/06/2021;BNP FP E;P;12;12;CONDORI;12;9:55:29;ETF;MINE;

I would like to separate this string into new cells of a each row on every semicolon detected in the same csv file.

Current code:

import sys, psycopg2

conn = psycopg2.connect("dbname=name user=userpassword=password")
cur = conn.cursor()

sql = "COPY (SELECT * FROM trades WHERE \"DATE_TRADE\" = '6/3/2021') TO STDOUT WITH CSV DELIMITER ';'"
with open(r'Y:\RESULT.csv', "a+") as file:
    cur.copy_expert(sql, file)
    array = file.readlines()
    array = [row.split(';') for row in array]

Yields a file that has all the records but not separated on each semi-colon

Any help is greatly appreciated

daniel
  • 37
  • 2
  • 9
  • Why do you not use the csv module from the standard library? – mkrieger1 Jun 03 '21 at 13:20
  • 1
    Does this answer your question? [How do I read and write CSV files with Python?](https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python) – mkrieger1 Jun 03 '21 at 13:22
  • 3
    But more importantly, why do you not read the data from the database directly into your program, instead of writing it to a CSV file and reading it again? – mkrieger1 Jun 03 '21 at 13:25
  • 1
    `cur.execute('SELECT ...').fetchall()` should be enough... – Serge Ballesta Jun 03 '21 at 13:26

1 Answers1

-1
with open("data.csv") as file:
    contents = file.read().split("\n")
array = [c.split(";") for c in contents]
not_speshal
  • 22,093
  • 2
  • 15
  • 30
  • 2
    Please do not blindly advise to use `split` to parse an arbitrary csv file, when the CSV module is much more robust and cares for separators or new lines inside fields. – Serge Ballesta Jun 03 '21 at 13:25