0

I would like to print all the tests that a user has participated in. This is my code:

def report(testFile, userEntry):
    testFile = open("test.txt", "r")
    for line in testFile:
        lineWithoutNewLine = line.rstrip('\n')
        userRecord = lineWithoutNewLine.split(';')  # making the line a list
        userName = userRecord[0]
        subject = userRecord[1]
        user = userRecord[2]
        score = userRecord[3]
        grade = userRecord[4]

   if userRecord[0] == userEntry: 
        testFile = open("test.txt", "r") 
        print(userRecord)

More code that may give more insight into my program:

if (subject == 'history' or subject == 'History') and (unit == 'WWII' or unit == 'ww2'):
    with open("hisEasy.txt", "a") as hisWw2File:
        for hisEasy in quizzes:
            userName = hisWw2[0]
            subject = hisWw2[1]
            unit = hisWw2[2]
            score = hisWw2[3]
            grade = hisWw2[4]
            hisWw2File.write(userName + ';' + subject + ';' + unit + ';' + str(score) + ';' + grade + '\n')

if subject == 'history' or subject == 'History' and unit == 'Hitler' or unit == 'hitler':
with open("hisMedium.txt", "a") as hisMediumFile:
        for hisH in tests:
            userName = hisH[0]
            subject = hisH[1]
            unit = hisH[2]
            score = hisH[3]
            grade = hisH[4]
            hisHFile.write(userName + ';' + subject + ';' + unit + ';' + str(score) + ';' + grade + '\n')

The test file contains all the tests any user has every taken. For Example:

['qwe', 'history', 'ww2', '65', 'C'] 
['abc', 'maths', 'trigonometry', '80', 'A']

I want to go through all the tests and print all the tests that the username of the user currently logged in took. How would I improve my code to do this?

4
  • 2
    Your indenting is wrong. Commented Dec 31, 2017 at 21:22
  • 1
    @StephenRauch: I fixed it. @qwe: If you want help we need to see at least a sample of what is in quiz.txt. Commented Dec 31, 2017 at 21:26
  • @BoarGules I have improved my post to include a bit more detail :) Commented Dec 31, 2017 at 22:05
  • Your question is not very clear. Try to minimize the code and describe your specific problem. Show us 1. how the file looks like, 2. your code, 3. intended output. Commented Dec 31, 2017 at 23:42

1 Answer 1

2

One approach may be to structure the file storage as a csv file. Given the following contents in testfile.csv:

'username','subject','unit','score','grade'
'qwe', 'history', 'ww2', '65', 'C'
'abc', 'maths', 'trigonometry', '80', 'A'
'qwe', 'gatos', 'cat behavior', '32', 'F'
'abc', 'cooking', 'making sushi', '99', 'A'

Then here is a demonstration of using the csv standard library to conveniently handle reading contents of the file in a way that automatically retains the structure of the data as a dictionary. The column headers become the keys and each row's data becomes the values. In this case, the username of interest and filename are passed to a function which will return a list containing a dict for each test record found for that user. From there you have any number of options for how you want to process the information with the usual manipulations that apply to python dictionaries, though below it is only printed nicely for the sake of illustration.

import csv
from pprint import pprint # just pretty printing for demo

filename = 'testfile.csv'
user = 'abc'

def main():
  test_scores_list = get_scores(filename, user)
  if len(test_scores_list) > 0:
    print 'The following test scores have been found for user: {}'.format(user)
    for row in test_scores_list:
      pprint(row)
  else:
    print 'No tests found for user: {}.'.format(user)

def get_scores(filename, user):
  test_scores_list = []
  with open(filename, 'rb') as csvfile:
    datareader = csv.DictReader(csvfile, delimiter=',', quotechar='\'')
    for row in datareader:
      if row['username'] == user:
        test_scores_list.append(row)
  return test_scores_list

if __name__ == '__main__':
  main()

This snippet and sample input file will produce this output if you assign the username "abc" in the code:

The following test scores have been found for user: abc
{'grade': " 'A'",
 'score': " '80'",
 'subject': " 'maths'",
 'unit': " 'trigonometry'",
 'username': 'abc'}
{'grade': " 'A'",
 'score': " '99'",
 'subject': " 'cooking'",
 'unit': " 'making sushi'",
 'username': 'abc'}
Sign up to request clarification or add additional context in comments.

1 Comment

@M Doe Hi. Sorry to bother you but I've gotten this error: File "F:\COMPUTER SCIENCE - CA\Practice CA Program\Task 1 - QUIZ.py", line 15, in reportA with open(testFile, 'rb') as csvfile: TypeError: coercing to Unicode: need string or buffer, file found Any idea why?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.