How write file length in another file using a loop?

Question:

I am attempting to write a file which compares the amounts of permutations available for three numbers. The current script is

tmp = open("tmp_out.txt","w+")
out = open("output_trip.txt", "w")
N = 4
for k in range(2,N+1):
    count = 1
    for j in range(1,k):
        for i in range(0,j):
            tmp.write("({},{},{})n".format(i,j,k))
            count = len(tmp.readlines())
    out.write('{}{:10d}n'.format(k,count))

The desired output is something like

2      1
3      4
4      10

However, when I cat my outfile, I just get

2      0
3      0
4      0

When I try readline() outside of the loop, it counts one file appropriately, but I need it for more than one value. Is it something simple I’m missing?

I tried many variations of counting I found online but none of them would work in the loop. I’ve included just the simplest for this exercise.

I can just write a bash script to count which may be the easiest but I would prefer to get it done in python.

Asked By: docyftw

||

Answers:

jasonharper was correct. All it took was including tmp.seek(0) before the count to work. The correct version is:

N = 4
for k in range(2,N+1):
count = 1
for j in range(1,k):
    for i in range(0,j):
        tmp.write("({},{},{})n".format(i,j,k))
        tmp.seek(0)
        count = len(tmp.readlines())
out.write('{}{:10d}n'.format(k,count))

This code prints the number of ordered triples with a set upper limit (in this case 4). The structure of the original code writes the output of the function into a new file, then reads the file to check the length. However, after the loop is run, readlines() is at the end of the file. This is why it was giving 0’s for every value; there were no lines left at the end. It is necessary to reset to the beginning using tmp.seek(0) which then appropriately counts the lines (and thus the number of ordered triples for each value of N).

Answered By: docyftw