Reputation: 13
txt file is like this.
50 70 60
40 30 80
30 80 40
result txt file is like this.
50 70 60 60
40 30 80 50
30 80 40 50
I did like this so far. However I can't get result and also I cant' get the average
f=open("sample.txt")
lines=f.readlines()
for line in lines:
f2=open("result.txt", 'w')
for i in range(len(lines)):
each_score=line.split()
f2.write(str(map(int, each_score)))
f.close()
f2.close()
Upvotes: 1
Views: 37
Reputation: 5372
I had issues with your code so used what I could.
f=open("sample.txt")
lines=f.readlines()
f2=open("result.txt", 'w')
for line in lines:
line = line.strip()
if line == '':
continue
# Set each value as an integer into a list.
each_score = [int(num) for num in line.split()]
# Get average from sum/length.
avg = int(sum(each_score) / len(each_score))
# Create output list with item as str and include avg.
output = [str(item) for item in (each_score + [avg])]
# Finally write the line by joining the values.
f2.write(' '.join(output) + '\n')
f.close()
f2.close()
Commented for your understanding.
output:
50 70 60 60
40 30 80 50
30 80 40 50
Upvotes: 1