我正在尝试在.txt文件中写入,然后按字母顺序对内部名称进行排序,然后打印。我该怎么办?如果不能做到,还有其他选择吗?
print("Well done " + name + "! your total score is: {}/10 :)\n".format(score))
#os.system("color 0a")
time.sleep(3)
file = open(str(age) + ".txt" , "a") # Creates a file.txt if it hasn't already been created and ammends it 'a'
file.write(name + " " + str(age) + " {}\n".format(score)) # Writes into the file, .format(x) replaces {} with the variable x
file.close
f = open(str(age) + ".txt" , "r")
lines = f.readlines()
f.close()
lines.sort()
f = open(str(age) + ".txt" , "w")
for line in lines:
f.write(line)
print(lines)
f.flush()
f.close()
答案 0 :(得分:0)
我猜测输入看起来像 -
a 10 1
b 10 2
c 10 8
d 10 5
确保每个名称都在一个单独的行上,这似乎与您的代码不同,因为file.write()不会自动将\n
附加到结尾,您必须手动做到了 -
file.write(name + " " + str(age) + " {}\n".format(score))
然后你可以做 -
f = open(str(age) + ".txt" , "r")
lines = f.readlines()
f.close()
lines.sort()
f = open(str(age) + ".txt" , "w")
for line in lines:
f.write(line)
f.flush()
f.close()
答案 1 :(得分:0)
import random, time, operator, os # Import modules required for specific tasks
def quiz():
score = 0
for q in range (1,11): # 'for' loop: Repeats the lines between 0 to 11 times- 10 times
ops = {'+':operator.add,
'-':operator.sub,
'*':operator.mul}
op = random.choice(list(ops.keys()))
if op != '*': # != means 'not equal'
r1 = random.randint (-1, 100) # Randomises a number from -1 to 100
r2 = random.randint (-1, 100)
answer = ops.get(op)(r1,r2)
else:
r1 = random.randint(-1,12)
r2 = random.randint(-1,12)
answer = ops.get(op)(r1,r2)
if equ == answer :
score += 1
print("Correct, Well done, your score is: " + str(score))
elif end - start >= 20:
print("You took too long to answer.")
else:
print("Incorrect, Sorry. Your score is: " + str(score))
print("Well done " + name + "! your total score is: {}/10 :)\n".format(score))
time.sleep(3)
file = open(str(age) + ".txt" , "a") # Creates a file.txt if it hasn't already been created and ammends it 'a'
file.write(name + " " + str(age) + " {}".format(score)) # Writes into the file, .format(x) replaces {} with the variable x
file.close
f = open(str(age) + ".txt" , "r")
lines = f.readlines()
f.close()
lines.sort()
f = open(str(age) + ".txt" , "w")
for line in lines:
f.write(line)
print(lines)
f.flush()
f.close()
start = "" # Defines a variable
while start not in ('Y', 'y', 'yes', 'Yes') : # Repeats the lines beneath until the condition is met i.e.: input = 'y'
name = input("Welcome to the Maths Quiz! Please enter your name: \n").upper()
age = input("Enter your class number: 1, 2 or 3 \n")
while age not in ('1', '2', '3') :
age = input("Enter your class number: 1, 2 or 3 \n")
start = input("You are " + name + " in class: " + str(age) + "\nIs this right? Enter y=Yes or n=No \n" )
time.sleep(2)
print("Get ready! The Quiz will now begin!") # Displays on the screen
time.sleep(2)
quiz() # Runs the function quiz