简体   繁体   中英

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. 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. 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.

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 :

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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