python - 从 raw_input 变量的列表中删除数据

标签 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

但是,当创建临时列表时,它会存储诸如“example1\n”之类的数据,如果用户仅键入示例,它将无法工作。有没有更简单的方法来解决这个问题或解决这个问题?感谢您的帮助。

最佳答案

使用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

关于python - 从 raw_input 变量的列表中删除数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26620452/

相关文章:

python - 合并两行数据并连接值(如果唯一)-Pandas

python - 避免以前的文件

python - 如何在 python 中使用列表推导式规范化列表列表

python - 通过合并多个 (4) 个其他列表来创建新列表

python - 需要帮助将此函数应用于 Pandas 数据框列

python - 优化后评估 pyscipopt Expr

python - 系数分组 : coefficient equation from a longer expression

python - python 列表中的 Latex 表达式用于 matplotlib 中的标签

python - 欧拉计划 #255

python - 计算互相关函数?