2 回答
TA贡献1829条经验 获得超7个赞
列表.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
TA贡献1934条经验 获得超2个赞
我如何操作第一个字符串/数字 [...] 并同时保持上面的第二个字符串。
在替换点之前,您似乎可以在空格字符上拆分字符串,只修改您需要的部分。
例子:
s = "0192.4500.0010 ccu01.re1 "
numbers, host = s.split()
numbers = numbers.replace(".", "")
# TODO: fill in appropriate conversions with `numbers` here
print(numbers, host)
输出是:
019245000010 ccu01.re1
以供参考:
https://docs.python.org/3/library/stdtypes.html#str.split
我如何 [...] 在新行中保存输出行 (file2.write(line))
将输出写入文件时,不会自动添加换行符。您需要自己将它们添加到字符串中。
例子:
numbers = "{}.{}.{}.{}".format(*numbers)
line = "{} {}\n".format(numbers, host)
outf.write(line)
此外,使用with语句打开和最终关闭文件也是一个好习惯。
添加回答
举报