2017-11-02 3 views
0

초보자 인 Python입니다. 텍스트 파일을 csv으로 변환하는 스크립트를 작성하려고합니다. txt 로그의 형식은 다음과 같다 :변수를 파이썬에서 파일로 작성하십시오.

"수" "날짜" "시간", "인터페이스" "기원" "형" "액션" "서비스" "소스 포트" "소스", "대상" "프로토콜" "규칙" "규칙 이름" "현재 규칙 번호" "사용자" "정보" "제품" "원본 컴퓨터 이름" "원본 사용자 이름"

"176" "16Oct2017" "23:59:00 ""eth1 ""FWSIN2 ""로그 ""수락 ""TCP_135 ""62005 ""Host_10.2.2.68 ""10.168.150.135 ""tcp ""271 "" ""271-SINFW "" ""inzone : 내부 ; outzone : 외부; service_id : TCP_135 ""보안 게이트웨이/관리 "" "" "

나는 아래 스크립트 (in python3)을 작성했지만 작동하지는 않습니다. 그것은 화면에 잘 인쇄되지만 파일에 None을 인쇄합니다. 이 문제를 해결하기 위해이 코드를 어떻게 변경합니까?

import shlex 

socfile=open('samplelogs.txt',encoding='utf-8') 
csvfile=open('csvfile.csv',mode='w',encoding='utf-8') 
for strlist in socfile: 
    str=shlex.split(strlist) 
    for i in str: 
     myline=print(i,',',end='') 
    csvfile.write("%s" % myline) 
    #print(myline) 

socfile.close() 
csvfile.close() 
+1

들여 쓰기를 확인하십시오. 게시됨에 따라'csvfile.write'를 시작하는 줄은 루프 외부에 있습니다. 즉, 'myline'의 마지막 값으로 한 번만 실행됩니다. – nekomatic

+0

관리되지 않는 리소스를 사용할 때'with' 문을 사용해보십시오. –

+0

이 파일을 csv로 변환하려면 tsv를 bash로 csv로 변환하는 방법을 찾는 것이 좋습니다. 그것은 지금 나를 도망 간다. – HSchmale

답변

2

"print"함수는 문자열을 반환하지 않으므로 문자열을 파일에 인쇄합니다.

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) 

'myline'항상 '없음'값입니다 는 여기의 서명입니다. 대신을 시도해보십시오

import shlex 

socfile=open('test.txt',encoding='utf-8') 
csvfile=open('csvfile.csv',mode='w',encoding='utf-8') 
for strlist in socfile: 
    str=shlex.split(strlist) 
    for i in str: 
     print(i,',',end='', file=csvfile) 
    #csvfile.write("%s" % myline) 
    #print(myline) 

socfile.close() 
csvfile.close() 
1

당신은 파일을 읽고 쓰는 방언으로 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,, 
1

입력 파일이 빈 것 같다 여기

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 모듈을 사용하여 완벽한 예입니다 필드가있는 파일을 분리했다. 이중 따옴표로 묶여 있습니다. 이것은 CSV 모듈 자체로 쉽게 파싱 할 수 있습니다.

with open('samplelogs.txt',encoding='utf-8', newline='') as socfile, \ 
     open('csvfile.csv',mode='w',encoding='utf-8', newline='') as csvfile: 
    rd = csv.reader(socfile, delimiter = ' ', quoting=csv.QUOTE_ALL) # or "\t" if the delimiter is a tab 
    wr = csv.writer(csvfile) 
    for row in rd: 
     wr.writerow(row) 
관련 문제