停止时的python txt文件

时间:2014-02-01 13:34:07

标签: python while-loop

我正在寻找如何通过条件停止一段时间。停止在$ config1工作。 如何进入第一个!在节点$ config1之后?

def filtre(source):
fs = open(source, 'r')
while 1:
    txt = fs.readline()
    if txt =='':
        break

    else:
        print txt
        if txt == "$ config1\n":
            raw_input("==========================>")

            if txt == "!\n":
               raw_input("==========================>") 

fs.close()
return

txt文件

! ************************************
! *  Export File:  X:\test.txt
! *      Created by:  PC2
! *   Creation Date:  10/01/2014 18:50
! *            User:  test
! *************************************
!
!
$ config1
MCBR:54:62:2:32:.5:x34:y637::::
MCBR:54:62:2:32:.5:x34:y637::::
MCBR:54:62:2:32:.5:x34:y637::::
MCBR:54:62:2:32:.5:x34:y637::::
!
!
$ End of file.

2 个答案:

答案 0 :(得分:1)

谢谢,这段代码工作,:))

def filtre(source):
fs = open(source, 'r')
started = false
while 1:
    txt = fs.readline()
    if txt =='':
        break

    else:
        print txt
        if txt == "$ config1\n":
            started = true
            raw_input("==========================>")

            if started and txt == "!\n":
               break 

fs.close()
return

答案 1 :(得分:0)

你将其中一个if语句嵌套在另一个语句中,我认为你并不打算这样做。

“if,else if”在Python中可以写成:

if condition1:
    reaction1
elif condition2:
    reaction2

if condition1:
    reaction1
else:
    if condition2:
        reaction2

或者,如果您知道condition1condition2不能同时发生,那么这也是一样的:

if condition1:
    reaction1
if condition2:
    reaction2

缩进的程度很重要。