Python读取文件和删除项目

时间:2014-01-05 03:13:44

标签: python file

问题是编写一个程序,询问用户他们不喜欢的水果。接下来,阅读groceries.txt文件并创建一个名为groceries.new的新文件,其中包含用户不喜欢的水果。

到目前为止我写的是...我不知道如何从文件中删除该项目。

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()

2 个答案:

答案 0 :(得分:1)

这里的诀窍是你不是真的“删除”该项目。阅读完内容后,检查是否是用户不喜欢的水果。如果是,那么你不写入新文件;如果没有,那么你写入新文件。希望它有所帮助。

答案 1 :(得分:1)

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