【问题标题】:Remove bands below certain threshold in file删除文件中低于特定阈值的波段
【发布时间】:2020-06-02 17:16:25
【问题描述】:
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()

代码会将乐队的名称和乐谱写入文件。

如果乐队的分数低于用户给定的某个阈值,则它应该在文件中删除乐队的详细信息。希望你能帮忙。

提前谢谢你

【问题讨论】:

  • 所以你要求我们为你写完整的逻辑?如果您尝试一下会好得多,只有当您无法成功时,您才应该发布minimal reproducible example 以供我们帮助。
  • @ShadowRanger 我可以通过 data = line.split(",") 和 if data[1] > threshold: 来查询文件。但是,我不知道如何从文件中删除这些行。

标签: python function file input


【解决方案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(  ))

显然,您需要进行多种数据类型和范围检查才能使程序健壮,但基本逻辑是这样的。

【讨论】:

  • 感谢您的回复。我需要打印所有乐队的整体文件,然后使用单独的函数并打印乐队的名称和得分高于阈值并删除其他的。所以你的建议是不可能的。
  • 在这种情况下,生成两个文件 - 一个包含完整列表,另一个包含过滤后的文件。仍然只有 2 个文件写入,而不是 2 个文件写入 + 1 个文件读取在您想要的方法中。
  • 很抱歉要坚持下去,但问题是我需要用户在制作文件后在将被调用的函数中输入阈值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-30
  • 2016-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-21
  • 1970-01-01
相关资源
最近更新 更多