I have a list of strings in a text file. The strings are morning, night, sun, moon. What I am trying to do is to replace one of these strings with another string. For example, I would input morning to remove and replace it with afternoon. I am getting an error saying "builtins.ValueError: list.remove(x): x not in list" when the string clearly is in the list.
def main():
x = input("Enter a file name: ")
file = open(x , "r+")
y = input("Enter the string you want to replace: ")
z = input("Enter the string you to replace it with: ")
list = file.readlines()
list.remove(y)
list.append(z)
file.write(list)
print(file.read())
main()
If there is a better way of achieving the same results doing it another way, let me know. Thanks for the help!
listbecauselist()is a built-in function. Second, your strings inlisthave line breaks'\n'at the end. You should strip them off before attempting theremove.