Python脚本从文本文件到grep字段并在csv文件中写入输出

时间:2019-07-15 12:01:49

标签: python-3.x python-2.7 scripting python-2.6

我正在编写一个python脚本。需要您的帮助来更正python 3.x或python 2.6中的脚本

对于每个输入文件,需要在另一个目录中有单独的输出文件
我们有多个名称为suppose(1.1.1.2.txt,1.1.1.3.txt)的输入文件,其中一组相同的数据用空行分隔
需要从输入文件(文本文件)的行下面grep 并保持“来自用户的平均汇率(bps)”作为列标题,并保留“ 17104773”作为其行中的值,类似地,另一列中的“向用户的平均汇率(bps)”具有标题,而将其“ 247272821”的值保留在另一CSV文件。

MSYS2-64

输入文件:运行命令后

session: 43  ave rate from user(bps) : 17104773      ave rate to user(bps)   : 247272821

需要grep并将43放在输出文件的第一列中。这是动态值43

show sub data-rate smgr-instance 43

我的代码:

[local]AM-SI-SP-01# show sub data-rate smgr-instance 43
Thursday July 1 17:10:45 IST 
Total Subscribers       : 2978
Active                  : 2978          Dormant                 : 0
peak rate from user(bps): n/a*          peak rate to user(bps)  : n/a*
ave rate from user(bps) : 17104773      ave rate to user(bps)   : 247272821
sust rate from user(bps): 16999794      sust rate to user(bps)  : 246777077
peak rate from user(pps): n/a*          peak rate to user(pps)  : n/a*
ave rate from user(pps) : 13117         ave rate to user(pps)   : 27879
sust rate from user(pps): 13233         sust rate to user(pps)  : 27976

[local]AM-SI-SP-01# show sub data-rate smgr-instance 45
Thursday July 1 17:10:45 IST 
Total Subscribers       : 2978
Active                  : 2978          Dormant                 : 0
peak rate from user(bps): n/a*          peak rate to user(bps)  : n/a*
ave rate from user(bps) : 17104234      ave rate to user(bps)   : 24728978
sust rate from user(bps): 16999794      sust rate to user(bps)  : 246777077
peak rate from user(pps): n/a*          peak rate to user(pps)  : n/a*
ave rate from user(pps) : 13117         ave rate to user(pps)   : 27879
sust rate from user(pps): 13233         sust rate to user(pps)  : 27976

csv文件中的预期输出:

import os
import csv
import re
from io import BytesIO

def parseFile(somefile):

    data = dict()
    with open(somefile, 'r') as f :

        lines=f.read()
        sub="ave rate from user(bps)"
        if (lines.find(sub))==-1:
            print ("nothing")
        else:
            splitted = lines.split(':')
            data["Hostname"] = splitted[1]
            print (data)



        #print("mylines",lines)
        for line in lines:


            line = line.rstrip("\n")
            print ("line",line)
            #print (lines)
            #print (type(line))


            if (lines.startswith(sub)):
                print ("nothing")

            #continue;
            else:



                print (data)
        #return data
    #print (data)

parseFile("C:\\Users\\ajachaud\Desktop\\scripts\\abc\\fileName.txt")

if __name__ == "__main__":
    inputsDirectory = "C:/Users/ajachaud/Desktop/scripts"
    path = os.path.abspath(inputsDirectory)
    fileList = ["{}/{}".format(path,x) for x in os.listdir(inputsDirectory)]
   # print(fileList)

    # Load Each File and Build Dictionary
    csvRows = []
    for file in fileList:
        newRow = parseFile(file)
        csvRows.append(newRow)

   # print(csvRows)

    # Output CSV using dictionaries for each file
    outputFile = "output.csv"
    with open(outputFile, 'w', newline='') as csvfile:
        fieldnames = ["Hostname",
                      "loopback"]
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)

        writer.writeheader()
        for row in csvRows:
            writer.writerow(row)

1 个答案:

答案 0 :(得分:0)

使用正则表达式。

例如:

import re
import csv


with open("infile.txt") as infile, open("outfile.csv", "w") as outfile:
    data = infile.read()     #Read infile content
    ave_rate_from_user = re.search(r"ave rate from user\(bps\)\s*:\s*(\d+)\b", data)     #Search for `ave rate from user`
    if ave_rate_from_user:
        ave_rate_from_user = ave_rate_from_user.group(1)
    ave_rate_to_user = re.search(r"ave rate to user\(bps\)\s*:\s*(\d+)\b", data)  #Search for `ave rate to user`
    if ave_rate_to_user:
        ave_rate_to_user = ave_rate_to_user.group(1)

    writer = csv.writer(outfile)
    writer.writerow(["ave rate from user(bps)", "ave rate to user(bps)"])  #Write Header
    writer.writerow([ave_rate_from_user, ave_rate_to_user])    #Write Content
  • 应该与问题中提到的python的两个版本一起使用。