당신은 파일을 읽고 쓰는 방언으로 csv
모듈을 사용할 수 있습니다. csv-handling 코드를 직접 다시 작성하지 않으면 오류가 발생하지 않을 것입니다.
버그를 해결하는 대신 이렇게 :
csvfile.write(','.join(str) + '\n')
여기에 더 파이썬으로 다시 전체 프로그램입니다. 필드 주위에 따옴표가 포함되어 있지 않지만 직접 추가 할 수 있습니다. 그렇다면 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'의 마지막 값으로 한 번만 실행됩니다. – nekomatic
관리되지 않는 리소스를 사용할 때'with' 문을 사용해보십시오. –
이 파일을 csv로 변환하려면 tsv를 bash로 csv로 변환하는 방법을 찾는 것이 좋습니다. 그것은 지금 나를 도망 간다. – HSchmale