小编DPl*_*eis的帖子

用新字符串替换文件中的字符串

我有一个文本文件中的字符串列表。弦是早晨、夜晚、太阳、月亮。我想要做的是用另一个字符串替换这些字符串之一。例如,我会输入morning 以将其删除并替换为下午。当字符串明显在列表中时,我收到一条错误消息:“builtins.ValueError: list.remove(x): x not in 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()
Run Code Online (Sandbox Code Playgroud)

如果有更好的方法可以通过另一种方式实现相同的结果,请告诉我。谢谢您的帮助!

python replace file python-3.x

4
推荐指数
1
解决办法
8019
查看次数

标签 统计

file ×1

python ×1

python-3.x ×1

replace ×1