python3 txt文本转csv

把每一行转成一个list,然后直接写入csv文件即可,有表头的把表头转换成list写入就行。

数据是逗号间隔的:

这么一个简单的功能我找半天也找不到能用的代码,写博客的人不知道怎么想的?

import csv


if __name__ == "__main__":
    inputfile = 'NSL-KDD\\KDDTrain+.txt'
    outputfile = 'preprocessing\\p_KDDTrain+.csv'
    row=['duration','protocol_type','service',
    'flag','src_bytes','dst_bytes',
    'land','wrong_fragment','urgent',
    'hot','num_failed_logins','logged_in',
    'num_compromised','root_shell',
    'su_attempted','num_root','num_file_creations',
    'num_shells','num_access_files','num_outbound_cmds',
    'is_host_login','is_guest_login','count',
    'srv_count','serror_rate','srv_serror_rate',
    'rerror_rate','srv_rerror_rate','same_srv_rate',
    'diff_srv_rate','srv_diff_host_rate','dst_host_count',
    'dst_host_srv_count','dst_host_same_srv_rate','dst_host_diff_srv_rate',
    'dst_host_same_src_port_rate','dst_host_srv_diff_host_rate','dst_host_serror_rate',
    'dst_host_srv_serror_rate','dst_host_rerror_rate','dst_host_srv_rerror_rate',
    'label']

    csvfile = open(outputfile, 'w',newline='')
    writer = csv.writer(csvfile)
    writer.writerow(row)
    lines = open(inputfile, 'r', encoding='utf-8').readlines()
    for line in lines:
        csvfile.write(line)
    csvfile.close()


 
    
    
    

 

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页