所以我对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”这样的数据,如果用户只键入示例它就不起作用。有没有更简单的方法来解决这个问题?谢谢你的帮助。
答案 0 :(得分:1)
使用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
您还可以将换行符char连接到名称:
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