if else阻止代码执行问题

时间:2017-05-04 06:46:06

标签: python-3.x

我正在尝试运行以下代码,但它总是打印第一行2次,它永远不会进入elif语句。

import re

fileOpen = open('C:\\Python36\\execrice\\test2.txt')
str1 = '  switchport trunk allowed vlan'
str2 = '  switchport trunk allowed vlan add'
for line in fileOpen:
    if line.startswith(str1):
        print ("first line")
    elif line.startswith(str2):
        print ("second line")

文件内容

  switchport trunk allowed vlan 2,4-24,27,30-36,38-39,41-46,48-50
  switchport trunk allowed vlan add 74,678-680,1101-1114,1201-1251

2 个答案:

答案 0 :(得分:0)

str1str2的前缀。因此,如果elif条件为真,则if条件也将为真。翻转您的条件顺序,您的代码应该有效。

答案 1 :(得分:0)

我假设fileOpen是文件的行。

改变你的条件。您正在检查行是否以str1开头,然后是str2。但是,str2包含str1。所有以str2开头的行也是以str1开头的。

相关问题