我有一个文件有几个IP地址。在txt的4行中有大约900个IP。我希望输出为每行1个IP。我怎样才能做到这一点?基于其他的代码,我想出了这个室内用,但它无法becasue多个IP单线路:python解析文件的IP地址
import sys
import re
try:
if sys.argv[1:]:
print "File: %s" % (sys.argv[1])
logfile = sys.argv[1]
else:
logfile = raw_input("Please enter a log file to parse, e.g /var/log/secure: ")
try:
file = open(logfile, "r")
ips = []
for text in file.readlines():
text = text.rstrip()
regex = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})$',text)
if regex is not None and regex not in ips:
ips.append(regex)
for ip in ips:
outfile = open("/tmp/list.txt", "a")
addy = "".join(ip)
if addy is not '':
print "IP: %s" % (addy)
outfile.write(addy)
outfile.write("\n")
finally:
file.close()
outfile.close()
except IOError, (errno, strerror):
print "I/O Error(%s) : %s" % (errno, strerror)
你要找的IPv4地址的规范形式。请注意,即使是IPv4地址,也有其他可接受的形式。例如尝试http:// 2130706433 /如果您在本地主机端口80上运行HTTP服务器(2130706433 == 0x7f000001 == 127.0.0.1)。当然,如果你控制文件的格式,你不需要担心这些事情......但是,如果你能够切实支持IPv6,它将会对你的脚本有前瞻性。 –
're.findall()'总是返回一个列表。它永远不是'没有'。 – jfs