简体   繁体   English

Python读取文件和删除项目

[英]Python Reading files and deleting items

The question is write a program that will ask the user for a fruit they dislike. 问题是编写一个程序,询问用户他们不喜欢的水果。 Next, read the groceries.txt file and create a new file called groceries.new with the fruit that the user dislikes removed. 接下来,阅读groceries.txt文件并创建一个名为groceries.new的新文件,其中包含用户不喜欢的水果。

what i written so far is... I don't know how to delete the item from the file. 到目前为止我写的是...我不知道如何从文件中删除该项目。

groceries = open('groceries.txt', 'r')

groceries_contents = groceries.read()

groceries_new = open('groceries.new.txt', 'w')

groceries_new.write(groceries_contents)

groceries_new_contents = groceries_new.read()

fruit = raw_input ("What fruit do you dislike? ")
if fruit in groceries_new_contents:
     del fruit 


groceries.close()
groceries_new.close()

The trick here is you are not really "delete" the item. 这里的诀窍是你不是真的“删除”该项目。 After you have read the content, you check whether it is the fruit the user dislikes. 阅读完内容后,检查是否是用户不喜欢的水果。 If yes, then you do not write to the new file; 如果是,那么你不写入新文件; if not, then you write to the new file. 如果没有,那么你写入新文件。 Hope it helps. 希望能帮助到你。

fruit = raw_input("What fruit do you dislike? ")
with open("groceries.txt") as file, open("groceries.new", "w") as output_file:
    for line in file:
        if fruit not in line: 
            output_file.write(line) # save line if it doesn't contain the fruit

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

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