あなたはあなたのファイルを読み書きする方言でcsv
モジュールを使用することができます。 csv-handlingコードを自分で書き直すのではなく、エラーが発生しにくくなります。あなたのバグに対処
、代わりにこれを行う:
csvfile.write(','.join(str) + '\n')
をここでより多くのニシキヘビに書き換えあなたの全体のプログラムがあります。フィールドの周りに引用符は含まれませんが、あなた自身で追加することができます。しかし、その後、csvモジュールを使用して、すべてのことをあなたに任せましょう。
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)
ここで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,,
インデントを確認します。投稿されると、 'csvfile.write'で始まる行はループの外側にあります。つまり、' myline'の最後の値で1回だけ実行されます。 – nekomatic
アンマネージドリソースを扱うときに 'with'ステートメントを使ってみてください。 –
このファイルをcsvに変換するには、tsvをbashでcsvに変換する方法を調べる方がよい場合があります。それは私の瞬間を逃れます。 – HSchmale