简体   繁体   English

如何使用用户输入从文件中删除内容

[英]How to remove things from file with user input

I have created a file with content.我创建了一个包含内容的文件。 The problem is that I know how to add things with append but I don't know how to remove things from the file with a user input.问题是我知道如何使用append添加内容,但我不知道如何使用用户输入从文件中删除内容。

The code is, the results variable is dictionary:代码是, results变量是字典:

    while True:
    remover = int(input("What results do you want to remove "))

    for line in enumerate(results, start = 1):
        line.remove(remover)
        print("{}".format(remover) + " is removed")

Would appreciate some help希望得到一些帮助

This seems like something that lends itself pretty well for a list comprehension.这似乎非常适合列表理解。

Assuming that results is a list of all the current results Please see the example below:假设结果是所有当前结果的列表请看下面的例子:

while True:
    remover = input("What results do you want to remove ")
    results = [line for line in results if line != remover]
    print("{}".format(remover) + " is removed")
    print("List currently has the following elements {}".format(results)

In the example below, for every iteration of the loop:在下面的示例中,对于循环的每次迭代:

  • The user is asked for input on what to remove要求用户输入要删除的内容
  • A new list is created and put in 'results' by using a list comprehension that creates a new list out of elements that do not match with whatever is in 'remover'通过使用列表推导式创建一个新列表并将其放入“结果”中,该列表推导式从与“remover”中的任何内容不匹配的元素中创建一个新列表
  • A message is shown explaining what was removed and another that prints the current list将显示一条消息,说明已删除的内容和打印当前列表的另一条消息

For more information on how list comprehensions work, please see: https://www.pythonforbeginners.com/basics/list-comprehensions-in-python有关列表推导如何工作的更多信息,请参阅: https : //www.pythonforbeginners.com/basics/list-comprehensions-in-python


If however you just want to get your example to work, you can refactor it into this:但是,如果您只想让您的示例工作,您可以将其重构为:

while True:
remover = int(input("What results do you want to remove "))

    for line in results:
        if line == remover:
            results.remove(remover)
            print("{}".format(remover) + " is removed")

What I changed here:我在这里改变了什么:

  1. I've moved your for statement into the while block, since I assume that with every iteration you want this to happen (why the while was there), additionally because you used a while(true) you would never execute the for block我已经将你的 for 语句移到了 while 块中,因为我假设在每次迭代中你都希望这种情况发生(为什么 while 在那里),另外因为你使用了 while(true) 你永远不会执行 for 块
  2. I've changed the for statement for a foreach since this simplifies things a lot.我已经更改了 foreach 的 for 语句,因为这大大简化了事情。

Please note that if you're not working with a list of integers, but strings you need to remove the typecasting to an int请注意,如果您不使用整数列表,而是使用字符串,则需要将类型转换删除为 int

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM