Reputation:
My goal is to have one program ask for inputs for test averages and write them to a txt file, and a second program that uses a loop to read and process the tests.txt file from the first program into a two-column table showing the test names and scores accurate to one decimal place.
What would the second program that reads the txt file look like?
Here is my code for the first program:
def main():
outfile =open('test.txt', 'w')
print('Entering six tests and scores')
num1 = float(input('Enter % score on this test '))
num2 = float(input('Enter % score on this test '))
num3 = float(input('Enter % score on this test '))
num4 = float(input('Enter % score on this test '))
num5 = float(input('Enter % score on this test '))
num6 = float(input('Enter % score on this test '))
outfile.write(str(num1) + '\n')
outfile.write(str(num2) + '\n')
outfile.write(str(num3) + '\n')
outfile.write(str(num4) + '\n')
outfile.write(str(num5) + '\n')
outfile.write(str(num6) + '\n')
outfile.close()
main()
And my second program:
def main():
infile = open('test.txt' , 'r')
line1 = infile.readline()
line2 = infile.readline()
line3 = infile.readline()
line4 = infile.readline()
line5 = infile.readline()
line6 = infile.readline()
infile.close()
line1 = line1.rstrip('\n')
line2 = line2.rstrip('\n')
line3 = line3.rstrip('\n')
line4 = line4.rstrip('\n')
line5 = line5.rstrip('\n')
line6 = line6.rstrip('\n')
infile.close()
main()
Upvotes: 0
Views: 340
Reputation: 3698
First of all, there is definitely no need to repeat yourself like that - a simple loop will save you from writing such repetitive code. Nevertheless, you may want to consider using a dictionary, since that is a go-to data structure for situations like these where you need to map keys (names) to values (scores). Also, you may want to consider using with
statement as a context manager, because it will automatically close the file for you after the nested block of code.
So, taking all that into account, something along the following lines should do the trick:
def first():
print('Entering six tests and scores')
my_tests = {}
for i in range(6):
name, score = input('Enter name and score, separated by a comma: ').split(',')
my_tests[name] = round(float(score), 1)
with open('tests.txt', 'w') as f:
for name, score in my_tests.items():
f.write('{} {}\n'.format(name, score))
...and when it comes to the second part of your problem:
def second():
with open('tests.txt', 'r') as f:
tests = f.readlines()
for row in tests:
test = row.rstrip('\n').split()
print('{}\t{}'.format(test[0], test[1]))
Upvotes: 2