numberofbands = int(input("How many bands are there in the competition? "))
print("Input each band’s name pressing enter after each one")
file = open("scores.txt","w")
for loop in range(numberofbands):
name = input("\nEnter the name of the band: ")
votes = input("Enter how many votes that band received: ")
file.write(name + "," + votes + "," + "\n")
file.close()
number_of_lines = len(open("scores.txt").readlines( ))
def removebelowthreshold():
threshold = int(input("Choose the threshold of scores to remove bands which are below"))
removebelowthreshold()
该代码将采用乐队的名称并将其记分到文件中。
然后,如果乐队的分数低于用户指定的某个阈值,则应在文件中删除乐队的详细信息。希望您能提供帮助。
提前谢谢
答案 0 :(得分:1)
为什么要先写文件,然后才尝试过滤文件?文件I / O操作在逻辑上是更昂贵的操作,因此您应将它们最小化。您应该在其他输入之前要求阈值,然后在文件写入循环中添加一个条件:
threshold = int(input("Choose the threshold of scores to remove bands which are below"))
numberofbands = int(input("How many bands are there in the competition? "))
print("Input each band’s name pressing enter after each one")
file = open("scores.txt","w")
for loop in range(numberofbands):
name = input("\nEnter the name of the band: ")
votes = input("Enter how many votes that band received: ")
if int(votes) >= threshold:
file.write(name + "," + votes + ",\n")
file.close()
number_of_lines = len(open("scores.txt").readlines( ))
很显然,您需要执行多种数据类型和范围检查才能使程序更健壮,但是基本逻辑是这样。