I need exactly the following actions by Python:
- Open the folder.
- Finding files with ".txt" format
- Open the found files.
- Reading a line from each file and adding numbers.
- Perform step 4 until the end of the files (5 lines).
- Dividing the obtained numbers by the number of opened files (Getting a grade point average).
- 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.