2017-04-21 146 views
0

我在这里找了几个小时寻找解决方案,但找不到一个解决方案。也许有人可以帮助我或指出类似的问题?while循环跳过python中的函数?

我有一个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 

...等等。

道歉,如果这其实是事先复制和感谢!

回答

1

为你的用例,你需要重新while循环里面的文件(addidionally我通过filehander 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) 
+0

那么快感谢您的帮助! – Sils10