从原始输入变量B的列表中删除数据

2024-03-28 13:24:29 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我对Python相当陌生。在阅读了一些不同的教程之后,我决定尝试制作一个简单的程序,其中的一个功能是删除txt文件中的一行。以下是我目前拥有的代码:

    name = raw_input("What name would you like to remove: ")
    templist = open("oplist.txt").readlines()
    templist_index = templist.index(name)
    templist.remove(templist_index)
    target = open("oplist.txt", "w")
    target.write(templist)
    target.close

但是,当创建templist时,它会存储“example1\n”之类的数据,如果用户只键入example,它将无法工作。有没有更简单的方法来解决这个问题?谢谢你的帮助


Tags: 文件代码name程序功能txttargetindex
1条回答
网友
1楼 · 发布于 2024-03-28 13:24:29

使用rstrip删除换行符并使用with打开文件:

with open("oplist.txt") as f: # with opens and closes the file automtically
    templist = [x.rstrip() for x in f] # strip new line char from every word

您还可以将换行符命名为:

templist_index = templist.index(name+"\n") # "foo" -> "foo\n" 

完整代码:

with open("oplist.txt") as f:
    temp_list = [x.rstrip() for x in f]
    name = raw_input("What name would you like to remove: ")
    temp_list.remove(name) # just pass name no need for intermediate variable
    with open("oplist.txt", "w") as target: # reopen with w to overwrite
        for line in temp_list: # iterate over updated list
             target.write("{}\n".format(line)) # we need to add back in the new line 
                                                # chars we stripped or all words will be on one line

相关问题 更多 >