今天看到同事使用word在替换txt文件中的字符,操作一番发现很麻烦,也不够自动化。于是做了个小需求来完成自动替换的需求,就是完成txt文本中所有IP地址后面添加掩码/24,便于从txt文件中的大量IP地址中导入其他工具中可以识别来进行配置。如果有更高的需求,可以使用IPy模块来完成更加复杂的功能。
基本功能的代码如下,即是定义函数Line_Add_Line,使用行的替换replace来完成删除原来的换行符,添加掩码后再添加换行符。函数分为三个部分:
1、读取原文件;
2、使用行替换字符并连接字符串;
3、再写入新文件中。
import os
def Line_Add_File(file,file_to,str):
file_data = ""
with open(file,"r") as fr:
for line in fr:
line = line.replace("\n",'') + str + "\n"
file_data = file_data + line
with open(file_to,"w") as fw:
fw.write(file_data)
filename = "IPs.txt"
filename_to = "添加掩码后文件.txt"
Line_Add_File(filename,filename_to,"/24")

网友评论