简体   繁体   中英

How can I list a string in .txt to .csv format using Python?

Here inside of my.txt file are bunch of strings:

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]

I'm trying to trim those sha1 and description then put it in a .csv file like this here in output:

这是一个示例输出csv

How can I get those string using if(after "\\" and before "->") then place it in csv, it's very hard and I can't think of an easier way.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM