您可以使用带方言的csv模块来读写文件。如果不自己重写csv处理代码,则不太容易出错。在
要解决您的错误,请执行以下操作:csvfile.write(','.join(str) + '\n')
这是你的整个程序被重写为更具Python特征的程序。它不包括字段周围的引号,但您可以自己添加它们。但是,只需使用csv模块,让它为您做一切。在
^{pr2}$
下面是一个使用csv模块的完整示例:#!/usr/bin/env python3
import csv
def convert(space_separated_file, csv_file):
class unix_space(csv.unix_dialect):
def __init__(self):
self.delimiter = ' '
input_rows = csv.reader(space_separated_file, dialect=unix_space())
output = csv.writer(csv_file, dialect='unix')
output.writerows(input_rows)
def example(in_filename, out_filename):
with open(in_filename) as f_in:
with open(out_filename, "w") as f_out:
convert(f_in, f_out)
def test():
with open('test.txt', 'w') as f:
f.write('''"Number" "Date" "Time" "Interface" "Origin" "Type" "Action" "Service" "Source Port" "Source" "Destination" "Protocol" "Rule" "Rule Name" "Current Rule Number" "User" "Information" "Product" "Source Machine Name" "Source User Name"
"176" "16Oct2017" "23:59:00" "eth1" "FWSIN2" "Log" "Accept" "TCP_135" "62005" "Host_10.2.2.68" "10.168.150.135" "tcp" "271" "" "271-SINFW" "" "inzone: Internal; outzone: External; service_id: TCP_135" "Security Gateway/Management" "" ""
''')
example('test.txt', 'test.csv')
with open('test.csv') as f:
print(f.read())
test()
输出:"Number","Date","Time","Interface","Origin","Type","Action","Service","Source Port","Source","Destination","Protocol","Rule","Rule Name","Current Rule Number","User","Information","Product","Source Machine Name","Source User Name"
"176","16Oct2017","23:59:00","eth1","FWSIN2","Log","Accept","TCP_135","62005","Host_10.2.2.68","10.168.150.135","tcp","271","","271-SINFW","","inzone: Internal; outzone: External; service_id: TCP_135","Security Gateway/Management","",""
您的输出:Number,Date,Time,Interface,Origin,Type,Action,Service,Source Port,Source,Destination,Protocol,Rule,Rule Name,Current Rule Number,User,Information,Product,Source Machine Name,Source User Name
176,16Oct2017,23:59:00,eth1,FWSIN2,Log,Accept,TCP_135,62005,Host_10.2.2.68,10.168.150.135,tcp,271,,271-SINFW,,inzone: Internal; outzone: External; service_id: TCP_135,Security Gateway/Management,,