2 回答

TA貢獻1829條經(jīng)驗 獲得超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到同一個文件,可以創(chuàng)建兩個單獨的列表來存儲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條經(jīng)驗 獲得超2個贊
我如何操作第一個字符串/數(shù)字 [...] 并同時保持上面的第二個字符串。
在替換點之前,您似乎可以在空格字符上拆分字符串,只修改您需要的部分。
例子:
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語句打開和最終關(guān)閉文件也是一個好習慣。
添加回答
舉報