我有一个由多行数据(systemid 和主机名)组成的文件(sysid.txt),如下所示
0192.4500.0000 uue01.re1
0192.4500.0010 ccu01.re1
0192.4500.0110 uue02.re1
0192.4500.0001 core1.re2
根据此处的信息和帮助,第一个字符串(数字)成功替换为需要但第二个字符串(主机名)丢失,并且当我运行下面的代码时,输出显示在单行中。
file1 = open('sysid.txt', 'r')
file2 = open('sysip.txt', 'w')
file1_cont = file1.readlines()
for line in file1_cont:
line = line.replace('.', '')
f = itemgetter(slice(0,3), slice(3,6), slice(6,9), slice(9,12))
line = '.'.join(f(line.replace('.','')))
line = '{}.{}.{}.{}'.format(*map(int, f(line.replace('.', ''))))
file2.write(line)
print(line)
sysip.txt 的输出
10.89.0.010.89.0.110.89.0.3210.89.0.3310.89.0.3410.89.0.3510.89.0.64
阅读每一行,我想替换第一个字符串(数字)并保持第二个字符串(主机名)如下
192.45.0.0 uue01.re1
192.45.0.10 ccu01.re1
192.45.0.110 uue02.re1
192.45.0.1 core1.re2
我如何操作第一个字符串/数字并将输出行(file2.write(line))保存在新行中,同时保持上面的第二个字符串。
感谢您的支持和指导。
#更新列表.txt...
System ID Hostname
0192.4500.0000 uue01.re1
0192.4500.0010 ccu01.re1
0192.4500.0110 uue02.re1
0192.4500.0001 core1.re2
{master}
列表.txt:
0192.4500.0000 uue01.re1
0192.4500.0010 ccu01.re1
0192.4500.0110 uue02.re1
0192.4500.0001 core1.re2
因此:
def removeZeros(ip):
# splits the ip by "."
# converts the words to integeres to remove leading removeZeros
# convert back the integer to string and join them back to a string
new_ip = ".".join([str(int(i)) for i in ip.split(".")])
return new_ip
logFile = "list.txt"
with open(logFile) as f:
content = f.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
for line in content:
line = line[1:].split(" ")[0]
line = removeZeros(line).replace(removeZeros(line).split(".", 2)[1],removeZeros(line).split(".", 2)[1][:-2] + ".0")
print(line)
输出:
192.45.0.0
192.45.0.10
192.45.0.110
192.45.0.1
编辑:
如果要将新 ip 覆盖list
到同一文件,可以创建两个单独的列表来存储ips
和text
:
logFile = "list.txt"
with open(logFile) as f:
content = f.readlines()
# you may also want to remove empty lines
content = [l.strip() for l in content if l.strip()]
ipList = []
stList = []
for line in content:
stList.append(line[1:].split(" ")[1])
line = line[1:].split(" ")[0]
line = removeZeros(line).replace(removeZeros(line).split(".", 2)[1],removeZeros(line).split(".", 2)[1][:-2] + ".0")
ipList.append(line)
# print(line)
with open(logFile, "w") as f:
for index in range(len(ipList)):
f.write(str(ipList[index]) + " " + str(stList[index]) + "\n")
输出(来自文件):
192.45.0.0 uue01.re1
192.45.0.10 ccu01.re1
192.45.0.110 uue02.re1
192.45.0.1 core1.re2
编辑 3:
为了删除第一行和最后一行,请使用切片:
替换这一行:
for line in content:
有了这个:
for line in content[1:-1]: # after the first and before the last line
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句