Python demo

import re
import csv

wholeList = []
csvFile = open(r"C:/Users/14526/Desktop/1.csv", "w", newline='')
writer2 = csv.writer(csvFile)
headerSet = set()

with open(r"C:/Users/14526/Desktop/jobStr.txt") as file:
    while 1:
        line = file.readline()
        if not line:
            break
        dic = {}
        surroundByQuote = re.findall("\"([^:]*?)\"", line)
        # "\"([^:]*?)\""
        if surroundByQuote:
            for item in surroundByQuote:
                newStr = item.replace(",", "^")
                line = line.replace(item, newStr)
        kvs = line.split(',')
        for item in kvs:
            kv = item.split(':')
            dic[kv[0]] = kv[1].replace('^', ',')
            headerSet.add(kv[0])
            # writer.writerow({'first_name': 'Baked', 'last_name': 'Beans'})
        wholeList.append(dic)

writer = csv.DictWriter(csvFile, fieldnames=headerSet)
writer.writeheader()
writer.writerows(wholeList)

 

posted @ 2017-10-16 23:20  Jiang_Xi  阅读(287)  评论(0编辑  收藏  举报