Skip to content Skip to sidebar Skip to footer

Python Split Function

I have problem 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'

Solution 1:

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]   

Solution 2:

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

Post a Comment for "Python Split Function"