簡體   English   中英

在使用Python讀取CSV文件時,如何轉義逗號?

[英]How do I escape commas while reading CSV files with Python?

我有一些CSV文件的gzip文件。 因此,我沒有使用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,但這不能解決問題。

為什么不將csv.readercsv.reader中的文件句柄gzip.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=',')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM