How to add lines containing numbers from a folder line by line with Python?

Question:

I need exactly the following actions by Python:

  1. Open the folder.
  2. Finding files with ".txt" format
  3. Open the found files.
  4. Reading a line from each file and adding numbers.
  5. Perform step 4 until the end of the files (5 lines).
  6. Dividing the obtained numbers by the number of opened files (Getting a grade point average).
  7. Write the result in the "finish.txt" file in the same folder.

I wrote a code but it doesn’t work. if you can fix it please do.
Also you can solve my problem by another code.

import os
path = str(os.path.dirname(__file__))+"\files"
os.chdir(path)
def sl (fp):
    path = str(os.path.dirname(__file__))+"\files"
    L=len([name for name in os.listdir(path) if 
os.path.isfile(os.path.join(path, name))])
    if L:
        if file.endswith(".txt"):
            Length=L
        else:
            Length=1
    finish=open(os.path.dirname(__file__)+"\finish.txt", 
"w")
    Sum1=0
    Sum2=0
    Sum3=0
    Sum4=0
    Sum5=0
    with open(file_path, 'r') as fp:
        line_numbers = [0, 1, 2, 3, 4]
        lines = []
        for i, line in enumerate(fp):
            if i in line_numbers:
                lines.append(line.strip())
                if i==0:
                    Sum1+=int(line)
                if i==1:
                    Sum2+=int(line)
                if i==2:
                    Sum3+=int(line)
                if i==3:
                    Sum4+=int(line)
                if i==4:
                    Sum5+=int(line)
            elif i > 4:
                break
        Write=str(int(Sum1/Length))+"n"+str(int(Sum2/Length))+"n"+str(int(Sum3/Length))+"n"+str(int(Sum4/Length))+"n"+str(int(Sum5/Length))+"n"

finish.write(Write+str((Sum1+Sum2+Sum3+Sum4+Sum5)/Length))
        finish.close()
    # iterate through all file
    for file in os.listdir():
    # Check whether file is in text format or not
    if file.endswith(".txt"):
        file_path = f"{path}{file}"
        sl(file_path)
Asked By: Aliakbar SMMS

||

Answers:

If you want, as I described, the average of all of the line 1s, and the average of all of the line 2s, etc, then this will do it.

Note that it is not necessary to specify a path each time, since you use chdir to make that the current directory. Note that I keep all of the sums in a list. ANY TIME you find your self using variables called xxx1, xxx2, xxx3 etc, you need to replace that set with a list. Finally, note that I wait until all the files have been read before computing the results.

import os
path = str(os.path.dirname(__file__))+"\files"
os.chdir(path)

sums = [0,0,0,0,0]
count = 0

for name in os.listdir('.'):
    if name.endswith(".txt"):
        count += 1
        for num, line in enumerate(open(name, 'r')):
            if num > 4:
                break
            sums[num] += float(line.strip())

finish = open("finish.txt",'w')
for i in sums:
    print( i/count, file=finish)
print(sum(sums) / count, file=finish)
finish.close()
Answered By: Tim Roberts