qwe
qwe

Reputation: 93

Searching Text Files in Python

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?

Upvotes: 0

Views: 90

Answers (1)

M Doe
M Doe

Reputation: 31

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'}

Upvotes: 2

Related Questions