How do I split a comma delimited string in Python except for the commas that are within quotes

后端 未结 4 1013
执笔经年
执笔经年 2020-12-20 01:07

I am trying to split a comma delimited string in python. The tricky part for me here is that some of the fields in the data themselves have a comma in them and they are encl

4条回答
  •  Happy的楠姐
    2020-12-20 01:53

    I fabricated something like this. Very redundant I suppose, but it does the job for me. You have to adapt it a bit to your specifications:

    def csv_splitter(line):
        splitthese = [0]
        splitted = []
        splitpos = True
        for nr, i in enumerate(line):
            if i == "\"" and splitpos == True: 
                splitpos = False
            elif i == "\"" and splitpos == False:
                splitpos = True
            if i == "," and splitpos == True:
                splitthese.append(nr)
        splitthese.append(len(line)+1) 
        for i in range(len(splitthese)-1):
            splitted.append(re.sub("^,|\"","",line[splitthese[i]:splitthese[i+1]]))
        return splitted
    

提交回复
热议问题