开发者

How to avoid splitting on a delimiter if it appears inside quotes?

开发者 https://www.devze.com 2023-02-22 18:14 出处:网络
I have pr开发者_StackOverflow中文版oblem in splitting data. I have data as follows in CSV file:

I have pr开发者_StackOverflow中文版oblem in splitting data. I have data as follows in CSV file:

"a";"b";"c;d";"e"

The problem is when I used line.split(";") function, it splits even between c and d. I don't want c and d to be separated. Later I need to store these four values in four different columns in a table, but using this function I get five different columns.

I want the results to be "a" "b" "cd" "e".

I tried with line.split('";"'), but it did not help.


import csv
reader = csv.reader(open("yourfile.csv", "rb"), delimiter=';')
for row in reader:
    print row

Try this out.

import csv
reader = csv.reader(open("yourfile.csv", "rb"), delimiter=';', quoting=csv.QUOTE_NONE )
for row in reader:
    print row

This ^^^ if you want quotes preserved

Edit: If you want ';' removed from the field content ('c;d' = 'cd' case) - you may do the post processing on rows returned, something like this:

import csv
reader = csv.reader(open("yourfile.csv", "rb"), delimiter=';', quoting=csv.QUOTE_NONE )
for row in reader:
    print [item.replace(';', '') for item in row]   


In other contexts, the shlex.split() function could be used

0

精彩评论

暂无评论...
验证码 换一张
取 消