我的任务是从多个文本文件创建NFS共享和关联IP的列表,并将其另存为CSV。该文件包含NFS共享名和IP以及我不希望包含在CSV中的其他数据

文本文件示例:


  / vol / vm-01
  -sec = sys,rw = 10.44.160.133:10.44.160.132:10.44.160.131:10.44.160.130,root = 10.44.160.133:10.44.160.132:10.44.160.131:10.44.160.130 / vol / vol01
  -sec = sys,rw = 10.44.202.39:10.44.202.73,root = 10.44.202.39:10.44.202.73


我已经使用了正则表达式,并且很容易地滤除了IP,但是找不到合并卷名的方法。


# Scrape file for IP's using RegEx
with open('input.txt') as f:
    qlist = [re.findall( r'[0-9]+(?:\.[0-9]+){3}', i ) for i in f.readlines()]
    for x in range(len(qlist)):
        print(qlist[x])


示例输出:


  ['10 .44.160.133','10.44.160.132','10.44.160.131','10.44.160.130',
  '10 .44.160.133','10.44.160.132','10.44.160.131','10.44.160.130']
  ['10 .44.202.39','10.44.202.73','10.44.202.39','10.44.202.73']


所需输出:


  ['vm-01','10.44.160.133','10.44.160.132','10.44.160.131',
  '10 .44.160.130','10.44.160.133','10.44.160.132','10.44.160.131',
  '10 .44.160.130'] ['vol01','10 .44.202.39','10 .44.202.73',
  '10 .44.202.39','10.44.202.73']

最佳答案

这是完成工作的一种方法:

import re

qlist = []
with open('input.txt') as f:
    for line in f.readlines():
        tmp = []
        # search the volume name
        m = re.search(r'/vol/(\S+)', line)
        tmp.append(m.group(1))
        # loop on all IPs
        for i in re.findall( r'[0-9]+(?:\.[0-9]+){3}', line ):
            tmp.append(i)
        qlist.append(tmp)
for x in range(len(qlist)):
    print(qlist[x])


输出:

['vm-01', '10.44.160.133', '10.44.160.132', '10.44.160.131', '10.44.160.130', '10.44.160.133', '10.44.160.132', '10.44.160.131', '10.44.160.130']
['vol01', '10.44.202.39', '10.44.202.73', '10.44.202.39', '10.44.202.73']

关于python - Python-将包含IP地址和不同数据的文本文件列表转换为CSV,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57156305/

10-11 19:45