如何使用Python将.txt格式的字符串列出为.csv格式?

时间:2018-09-28 04:08:22

标签: python

my.txt文件中包含一串字符串:

Setting Process Priority to NORMAL: Success 1

Successfully setting POL Flag to 0
VSGetVirusPatternInformation is invoked
Reading virus pattern from lpt$vpn.527 (2018/09/25) (1452700)



LPT$VPN Pattern Version : 1452700

Successfully setting POL Flag to 0
Scanning partition sector of disk C:VSGetDiskData() not defined.

Scanning boot sector of disk C:VSGetDiskData() not defined.




Scanning samples_extracted\07831df482f1a34310fc4f5a092c333eeaff4380-> 
(MS Office 1-0)->Found Virus [TROJ_CVE201711882.UHAOBHAO]

我正在尝试修剪这些sha1和说明,然后将其放在.csv文件中,如下所示:

This is a sample output csv

如何使用if(在“ \”之后和“->”之前)将这些字符串放入csv中,这非常困难,我想不出一种更简单的方法。

1 个答案:

答案 0 :(得分:0)

import csv

INPUTFILE = 'input.txt'
OUTPUTFILE = 'output.csv'
PREFIX = '\\'
DELIMITER = '->'

def read_text_file(inputfile):
    data = []
    with open(inputfile, 'r') as f:
        lines = f.readlines()

    for line in lines:
        line = line.rstrip('\n')
        if not line == '':
            line = line.split(PREFIX, 1)[-1]
            parts = line.split(DELIMITER)
            data.append(parts)

    return data

def write_csv_file(data, outputfile):
    with open(outputfile, 'wb') as csvfile:
        csvwriter = csv.writer(csvfile, delimiter=',', quotechar='"',
                                quoting=csv.QUOTE_ALL)
        for row in data:
            csvwriter.writerow(row)

def main():
    data = read_text_file(INPUTFILE)
    write_csv_file(data, OUTPUTFILE)

if __name__ == '__main__':
    main()