For example, my CSV file contains 4 lines:
CREATE TABLE test(col_name VARCHAR2(30) NOT NULL, col_name_2 INTEGER DEFAULT 0
NOT NULL);
CREATE TABLE test2(col_name VARCHAR2(30) NOT NULL, col_name_2 INTEGER DEFAULT 0
NOT NULL);
I'd like to split it by ";" in order to have 2 elements in the list. Can I do that using the standard csv.reader method? I know that I can use the Pandas.read_csv method.
My current code:
with open("my_file.csv", newline='', encoding="utf8") as csvfile:
reader = csv.reader(csvfile)
CodePudding user response:
You could do:
with open("my_file.csv", "r", newline='', encoding="utf8") as csvfile:
lines = csvfile.read().strip().rstrip(";").replace("\n", "").split(";")
Result:
['CREATE TABLE test(col_name VARCHAR2(30) NOT NULL, col_name_2 INTEGER DEFAULT 0 NOT NULL)',
'CREATE TABLE test2(col_name VARCHAR2(30) NOT NULL, col_name_2 INTEGER DEFAULT 0 NOT NULL)']
CodePudding user response:
I hope this solves your problem because the split ';' works for fields but not in your case.
import csv
with open("file.csv",encoding="utf8") as csvfile:
reader = csv.reader(csvfile)
count = 1
rows = []
for row in reader:
if count % 2 == 0 :
row1.append(" ".join(row))
rows.append(" ".join(row1))
row1 = []
else:
row1 = row
count = count 1
print(rows)