#!/usr/bin/python3
#-*- coding:utf8 -*-
import sys
import os
import socket
#编写环境 windows10 + Python3.5.3
# 在同一目录生成排序好的IP文件ip_newsort.txt
#输入如下 python3 ipsort.py ip.txt
iplist = []
def ipsort(iplist):
#写文件
with open('ip_newsort.txt','w') as file:
for i in sorted(iplist,key=socket.inet_aton):
print(i)
file.writelines(i+"\n")
#print(file)
def read_file(filename):
#读取文件
with open(filename,'r') as file:
for line in file:
iplist.append(line.rstrip('\n').rstrip('\n'))#清除格式转换成列表
return iplist
def main():
try:
if len(sys.argv) != 2:
print("Usage: %s %s" % (sys.argv[0],sys.argv[1]))
else:
# 判断文件路径是否存在,如果存在把文件全路径赋值给filename,否则直接退出
if os.path.exists(sys.argv[1]):
filename=sys.argv[1]
else:
print("%s is not exists!" % (sys.argv[1]))
sys.exit(1)
iplist=read_file(filename) #读取文件
#print(iplist)
ipsort(iplist) #执行排序函数调用
except Exception as e:
print(e)
if __name__ == '__main__':
main()
排序前:
排序后: