gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:07:17 27 4
gpt4 key购买 nike

所以我对 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com