如何在使用Python读取CSV文件时转义逗号?

时间:2015-11-02 20:45:50

标签: python csv

我有一些gzip文件是CSV文件。所以我没有使用csv模块。

某些字符字段封装在双引号中:",但不是全部。我的目标是读取行并基本上将数据复制到另一个文件。包含双引号的某些字段中包含逗号,而我的脚本不能正确忽略引号中的逗号。如何设置它以便Python忽略双引号中的字符?

这是与该问题有关的代码的一部分:

with gzip.open('gzippedfile.csv.gz', 'r') as campaign, open('output%s.csv' % today, 'wb') as output:
        outputwriter = csv.writer(output, delimiter=',')

    #Create variable 'count' to hold counter to skip reading the header line in the input file
        count = 0

        for line in campaign:
                line=line.replace('\"','')
                line=line.replace('\'','')
                #print line
                #Increment count by one each loop. This will make the loop skip the header line at the first iteration
                count = count+1
                if count == 1:
                        continue    
                #print today
        #Create strings of the campaignid, whitelist entry, blacklist entry, and zipcode list each row
                campaignid = line.split(',')[0].lstrip()
                whitelist = line.split(',')[10].lstrip()
                blacklist = line.split(',')[11]
                zipcodes = line.split(',')[12]

我已尝试删除replace第8行和第9行,但这并不能解决问题。

1 个答案:

答案 0 :(得分:4)

为什么不将csv.readergzip.open的文件句柄一起使用?

with gzip.open('gzippedfile.csv.gz', 'r') as campaign, open('output%s.csv' % today, 'wb') as output:
    reader = csv.reader(campaign)  # look ma' no manual escaping 
    outputwriter = csv.writer(output, delimiter=',')