name = input("please enter your name\n")
score1=input("please enter your first test score out of 10\n")
score2=input("please enter your second test score out of 10\n")
score3=input("please enter your third test score out of 10\n")
class_=input("please enter the name of your class either class1,class2 or class3\n")
if class_== ("class1"):
myfile=open("class1.txt","a")
myfile.write(name)
myfile.write("-")
myfile.write(score1)
myfile.write("-")
myfile.write(score2)
myfile.write("-")
myfile.write(score3)
myfile.write("-")
myfile.write(class_)
myfile.write("\n")
myfile.close()
elif class_== ("class2"):
myfile=open("class2.txt","a")
myfile.write(name)
myfile.write("-")
myfile.write(score1)
myfile.write("-")
myfile.write(score2)
myfile.write("-")
myfile.write(score3)
myfile.write("-")
myfile.write(class_)
myfile.write("\n")
myfile.close()
elif class_== ("class3"):
myfile=open("class3.txt","a")
myfile.write(name)
myfile.write("-")
myfile.write(score1)
myfile.write("-")
myfile.write(score2)
myfile.write("-")
myfile.write(score3)
myfile.write("-")
myfile.write(class_)
myfile.write("\n")
myfile.close()
else:
print("please eter a valid class name")
sorting = input("please enter the name of the class you wish to see\n")
if sorting ==("class1"):
myfile=open("class1.txt","r")
for line in myfile:
class_name = myfile.readline()
class_name.sort()
print (class_name)
myfile.close()
当我在python中运行代码时,它一直工作,直到我问我要选哪个类,当我选择第1类时,总是会出现第51行, class_name.sort(反向=真) AttributeError:' str'对象没有属性' sort' 我不知道如何解决这个问题。
答案 0 :(得分:0)
您不能在字符串上使用sort()
(需要list
),请使用:
>>> class_name = 'myclassname'
>>> class_name = ''.join(sorted(class_name))
>>> class_name
'aacelmmnssy'
如果您希望对所有行进行排序:
lines = sorted(myfile.readlines())
答案 1 :(得分:0)
这样的事情:
with open(myfile, 'r') as r:
for line in sorted(r):
print(line, end='')