【问题标题】:While loop jumps over function in python? [duplicate]while循环跳过python中的函数? [复制]
【发布时间】:2017-04-21 17:36:47
【问题描述】:

我在这里寻找了几个小时的解决方案,但找不到。也许有人可以帮助我或指出类似的问题?

我在 while 循环中有一个函数。该函数遍历文本文件中的每一行:

def parser():
    for line in f:
        print(line)

f = open('textfile.txt', 'r')

count = 0
while count < 7:
    parser()
    count += 1
    print(count)

我的输出如下:

text file line 1
text file line 2
text file line 3

1
2
3
4
5
6

我最初的目标是在每次 +1 后再次调用该函数:

text file line 1
text file line 2
text file line 3
1
text file line 1
text file line 2
text file line 3
2
text file line 1
text file line 2
text file line 3
3

...等等。

抱歉,如果这实际上是重复的,并提前感谢!

【问题讨论】:

    标签: python python-2.7 while-loop


    【解决方案1】:

    对于您的用例,您需要在 while 循环中重新打开文件(另外,我将文件处理程序 f 作为参数传递给 parser 函数):

    def parser(f):
        for line in f:
            print(line.strip())  # stripping off '\n'
    
    count = 0
    while count < 7:
        with open('../var/textfile.txt', 'r') as f:
            parser(f)
        count += 1
        print(count)
    

    或者,您也可以f.seek(0) 将原始文件保持打开状态:

    f = open('../var/textfile.txt', 'r')
    
    count = 0
    while count < 7:
        f.seek(0)
        parser(f)
        count += 1
        print(count)
    

    【讨论】:

    • 这么快-感谢您的帮助!
    猜你喜欢
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2013-01-29
    • 2022-01-06
    • 2013-03-19
    • 1970-01-01
    • 2021-05-04
    相关资源
    最近更新 更多