简体   繁体   English

如果第一个文件不是最后一行,Python从文件开头开始

[英]Python start from beginning of file if first file is not last line

with open(args.identfile) as indetifierfile, \
 open(args.elementtxt) as elementfile:
 for identifier_line, element_line in izip(identifierfile, elementfile):
    ident_split = identifier_line.split(".")
    el_split = elementfile_line.split(".")
    print ident_split[0]
    print ident_split[1]
    print el_split[0] //print for debug, bad programming practice apparently. I know.
    print el_split[1]
    if el_split is None: //tried to use this to start from the beginning of the file and continue loop? I don't know if it's valid.
        el_split.seek(0)

So I tried to read and process these two files. 因此,我尝试读取和处理这两个文件。 Where the print statements are I was going to put some code to put the stuff from the files together and output it to a file. 我将在打印语句所在的位置放一些代码,以将文件中的内容放在一起,然后将其输出到文件中。 The stuff in the element file doesn't have as much as identifier files. 元素文件中的内容没有标识符文件那么多。 I would like to start from the beginning of the element file everytime it reaches end of file? 我想从元素文件的开头开始,每次到达文件末尾? I'm not sure how to go about this I tried the .seek But that's not working. 我不确定如何解决这个问题,我尝试了.seek但是那没有用。 How do I go about doing this? 我该怎么做呢? To continue the loop and reading identifier file but start from the beginning of the element file. 要继续循环并读取标识符文件,但要从元素文件的开头开始。

I think the code below will do what you want. 我认为以下代码可以满足您的需求。 Get the length of the element file. 获取元素文件的长度。 Add to your counter every pass of the for loop. 将for循环的每一次通过添加到您的计数器中。 Once the counter reaches the length of the element file minus 1 (because arrays start at 0), it will reset the counter to 0 and start from the beginning of the elementfile while still going on the identifierfile. 一旦计数器达到元素文件的长度减去1(因为数组从0开始),它将把计数器重置为0,并从元素文件的开头开始,同时仍继续在标识符文件上。

count = 0
elementLength = len(elementfile)
for i in range(len(identifierfile)):
    ident_split = identifierfile[i].split(".")
    el_split = elementfile[count].split(".")
    print ident_split[0]
    print ident_split[1]
    print el_split[0]
    print el_split[1]
    if count < (elementLength-1):
        count = count + 1
    else:
        count = 0

You can try using itertools.cycle : 您可以尝试使用itertools.cycle

from itertools import izip, cycle

with open(args.identfile) as indetifierfile, \
 open(args.elementtxt) as elementfile:
 for identifier_line, element_line in izip(identifierfile, cycle(elementfile)):
    ident_split = identifier_line.split(".")
    el_split = elementfile_line.split(".")
    print ident_split[0]
    print ident_split[1]
    print el_split[0]
    print el_split[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM