You can use the csv module with dialects to read and write your files. It'll be less prone to error not rewriting csv-handling code yourself.
Addressing your bug, do this instead:
csvfile.write(','.join(str) + '\n')
Here's your entire program rewritten to be more pythonic. It doesn't include quotes around the fields, but you could add them yourself. But then, just use the csv module and let it do everything for you.
import shlex
with open('test.txt', encoding='utf-8') as socfile:
with open('csvfile.csv', mode='w', encoding='utf-8') as csvfile:
csvfile.writelines(','.join(shlex.split(line)) + '\n' for line in socfile)
Here's a complete example using the csv module:
#!/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()
Output:
"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","",""
Your output:
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,,
csvfile.writeis outside the loop, i.e. it will only execute once with the last value ofmyline.withstatement when working woth unmanaged resources.print(...)returnsNone.