我使用Python 2.7.6并学习使用csv
模块。当我将输入文件解析为每行中最后一个元素的CSV输出文件时,我的脚本以某种方式添加了意外的双引号和我的最后一个元素之后的几个空格。我无法使用常规替换删除这些双引号。
我可以删除额外双引号的唯一方法是使用:
tmp[1] = tmp[1][:-3]
我不明白在解析输入时如何添加额外的双引号。请告诉我当输入文件没有这些双引号时,为什么或如何将这些双引号添加到partno
。
我的代码:
import re
import csv
fname = "inputfile"
try:
fhand = open(fname)
except:
print 'File cannot be opened:', fname
exit()
domain = []
server = []
model = []
serial = []
dn = []
memsize = []
vid = []
partno = []
csv_out = open('/tmp/out.csv','wb')
writer = csv.writer(csv_out)
for line in fhand:
words = line.split("; ")
tmp_row_list = []
for number in [0,1,2,3,4,5,6,7]:
tmp=words[number].split("=")
if "}" in tmp[1]:
tmp[1] = tmp[1][:-3]
#tmp[1] = re.sub('}','', tmp[1])
if number == 0: domain.append(tmp[1])
if number == 1: server.append(tmp[1])
if number == 2: model.append(tmp[1])
if number == 3: serial.append(tmp[1])
if number == 4: dn.append(tmp[1])
if number == 5: memsize.append(tmp[1])
if number == 6: vid.append(tmp[1])
if number == 7: partno.append(tmp[1])
rows = zip(domain,server,model,serial,dn,memsize,vid,partno)
writer.writerows(rows)
csv_out.close()
输入文件:
ffile:@{Ucs=uname; ServerId=4/6; Model=UCSB-B200-M3; Serial=FCH; AssignedToDn=; TotalMemory=98304; Vid=V06; PartNumber=73-14689-04}
ffile:@{Ucs=uname; ServerId=4/7; Model=UCSB-B200-M3; Serial=FCH; AssignedToDn=; TotalMemory=98304; Vid=V06; PartNumber=73-14689-04}
我的错误的输出在我必须删除之前有奇怪的双引号(如果unrem与re.sub的行,带有双引号和额外空格的错误输出将显示在最后场/元件):
uname,4/6,UCSB-B200-M3,FCH,,98304,V06,"73-14689-04
"
uname,4/7,UCSB-B200-M3,FCH,,98304,V06,"73-14689-04
"
答案 0 :(得分:0)
看起来你可以简化那一批。
将input.txt
视为:
ffile:@{Ucs=uname; ServerId=4/6; Model=UCSB-B200-M3; Serial=FCH; AssignedToDn=; TotalMemory=98304; Vid=V06; PartNumber=73-14689-04}
ffile:@{Ucs=uname; ServerId=4/7; Model=UCSB-B200-M3; Serial=FCH; AssignedToDn=; TotalMemory=98304; Vid=V06; PartNumber=73-14689-04}
然后使用以下内容:
import re, csv
get_col_vals = re.compile('(?:\w+)=(.*?)[;}]').findall
with open('input.txt') as fin, open('output.csv', 'wb') as fout:
csvout = csv.writer(fout, quoting=csv.QUOTE_NONE)
csvout.writerows(get_col_vals(row) for row in fin)
结果output.csv
是:
uname,4/6,UCSB-B200-M3,FCH,,98304,V06,73-14689-04
uname,4/7,UCSB-B200-M3,FCH,,98304,V06,73-14689-04