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

Viewed 18

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 CalculateFilesLineByLine (fp):
    path = str(os.path.dirname(__file__))+"\\files"
    Length=len([name for name in os.listdir(path) if os.path.isfile(os.path.join(path, name))])
    if Length:
        if file.endswith(".txt"):
            l=1
        else:
            l=0
    finish=open(path+"\\finish.txt", "w")
    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:
                if l==1:
                lines.append(line.strip())
                    Sum=line
                    finish.write(str(Sum))
            elif i > 4:
                break
        finish.close()
# iterate through all file
for file in os.listdir():
    if file.endswith(".txt"):
    file_path = f"{path}\{file}"
        CalculateFilesLineByLine(file_path)

That was code but It doesn't work as I said.

0 Answers
Related