简体   繁体   中英

Split CSV file using standard csv.reader method

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)

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

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)

output: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM