我想打印用户参与的所有测试。这是我的代码:
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)
更多可以让我更深入了解我的计划的代码:
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')
测试文件包含用户每次测试的所有测试。 例如:
['qwe', 'history', 'ww2', '65', 'C']
['abc', 'maths', 'trigonometry', '80', 'A']
我想通过所有测试并打印当前登录用户的用户名所做的所有测试。如何改进我的代码呢?
答案 0 :(得分:2)
一种方法可能是将文件存储结构化为csv文件。给出 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'
然后,这里演示了使用csv标准库以一种自动保留数据结构作为字典的方式来方便地处理文件的读取内容。列标题成为键,每行的数据成为值。在这种情况下,感兴趣的用户名和文件名将被传递给一个函数,该函数将返回一个列表,其中包含为该用户找到的每个测试记录的字典。从那里你可以使用适用于python词典的常规操作来处理信息的任意数量选项,尽管下面仅为了说明而打印得很好。
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()
如果您在代码中指定了用户名“abc”,则此代码段和示例输入文件将生成此输出:
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'}