mercredi 22 juin 2016

How do I read an integer from a file, and then read that many lines after the integer in that file (Python)?


I'm having some trouble with this problem. I'm a beginner to Python and have been searching this website but can't seem to figure out how to do this specific problem. If I have a file that looks something like this:

3
Alpha
Beta
Gamma
4
Delta
Epsilon
Omega
Zeta

I want to read that first integer (in this case, 3 but it could vary) and print it, and then read the next three lines (Alpha, Beta, Gamma) and print those. After that, I would want to read the next integer (in this case, 4) and then read the next four lines (Delta, Epsilon, Omega, Zeta) and print those.

I think I've figured out how to do it if that integer is fixed, but I'm not sure how to do it if that integer is a variable and could be anything. Here is what I have for if the integer is fixed:

with open('myfile.txt') as input_data:
    for line in input_data:
        if line.strip() == '3':  
            print "3"
            break
# Reads text until the end of the block:
    for line in input_data:  # This keeps reading the file
        if line.strip() == '3':
            break
        print line

I would put this in a while loop that loops over the whole file, reading (and printing) an integer x, reading (and printing) the next x lines, then reading integer y, reading the next y lines, etc. Since I could be dealing with big files, it seems like reading line by line is the way to go with f.readline(), so after I read the first integer and numbers after it, I should read the next one.

Any help would be appreciated a lot. Thanks!

edit:

I would want to read from the file that has my data (3 Alpha Beta Gamma 4 etc). I would then read 3 (or any integer), which would then signal to read Alpha Beta Gamma. I would then write this to a file. Then, I would read 4 (or any integer again), which would then signal to read Delta Epsilon Omega Zeta. I would go through the rest of the file like this.

I have some idea for the individual parts, so after reading from file "myfile.txt", I would write this output to "output.txt":

with open('myfile.txt', 'r') as fin:
alllines = fin.readlines();
with open('output.txt', 'w') as fout:
    for i in range(len(alllines)):
            fout.write(alllines[i]);

I could also just do fin.readline() and read it line by line.


Aucun commentaire:

Enregistrer un commentaire