Python forloop只返回最后一行

时间:2015-04-27 20:00:40

标签: python

以下是我目前的代码。它应该读取文件,比较正则表达式,看看文本文件的输入是否是正确的IPv4地址。它工作正常,但只返回输入文件最后一行的输出。例如,如果输入文件如下所示:

 10.0.0.0
 255.255.255.255
 168.192.0.0

它只返回168.192.0.0是正确的。不是任何其他地址。谢谢。

**

import re

filename = input("Please enter the name of the file containing the input IP Addresses: ")
fo = open(filename, "r")


print()
for line in open(filename):
        pattern = '^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$'
m = re.match(pattern, line)
if m is not None:
        print("Match found - valid IP address: ", line, "\n")
else: print("Error - no match - invalid IP address: ",line, "\n")

fo.close

3 个答案:

答案 0 :(得分:1)

您需要将正则表达式匹配放在for循环中:

for line in open(filename):
        pattern = '^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$'
        m = re.match(pattern, line)
        if m is not None:
             print("Match found - valid IP address: ", line, "\n")
        else: print("Error - no match - invalid IP address: ",line, "\n")

fo.close

答案 1 :(得分:0)

print和re.match在循环之外,因此只打印最后一次迭代

for line in open(filename):
        pattern = '^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$'
        m = re.match(pattern, line)
        if m is not None:
            print("Match found - valid IP address: ", line, "\n")
        else: print("Error - no match - invalid IP address: ",line, "\n")

答案 2 :(得分:0)

想要进行一些格式更改,最好使用with打开文件。

import re
filename = input("Please enter the name of the file containing the input IP Addresses: ")
with open(filename) as fo:
    print()
    pattern = '^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$'
    for line in open(filename):
       if re.search(r"%s"%(pattern), line):
             print("Match found - valid IP address: ", line, "\n")
        else: print("Error - no match - invalid IP address: ",line, "\n")