[英]How do I escape commas while reading CSV files with Python?
I have some gzip files that are CSV files. 我有一些CSV文件的gzip文件。 So I'm not using the
csv
module. 因此,我没有使用
csv
模块。
Some character fields are encapsulated within double quotes: "
, but not all of them. My goal is to read the lines and basically copy the data to another file. Some of the fields that contain the double quotes have commas in them, and my script isn't properly ignoring commas within the quotes. How do I set it so Python ignores characters within double quotes? 有些字符字段封装在双引号中:
"
,但不是全部。我的目标是读取各行并将它们基本上复制到另一个文件中。某些包含双引号的字段中包含逗号,而我的脚本不能正确地忽略引号内的逗号。如何设置它以便Python忽略双引号内的字符?
This is part of the code pertaining to the question: 这是与该问题有关的代码的一部分:
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]
I've tried removing the replace
lines 8 and 9 but that doesn't fix the problem. 我试着删除
replace
行8和9,但这不能解决问题。
Why don't you use csv.reader
with the file handle from gzip.open
? 为什么不将
csv.reader
与csv.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.