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

DPl*_*eis 4 python replace file python-3.x

我有一个文本文件中的字符串列表。弦是早晨、夜晚、太阳、月亮。我想要做的是用另一个字符串替换这些字符串之一。例如,我会输入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)

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

Ray*_*ger 5

这里有一些想法:

这是一种方法:

import fileinput
import re

with fileinput.input(files=('file1.txt', 'file2.txt'), inplace=True) as f:
    for line in f:
        print( re.sub(y, z, line) )
Run Code Online (Sandbox Code Playgroud)

这是另一个想法:

  • 而不是逐行处理,只需将整个文件作为单个字符串读入,修复它,然后将其写回。

例如:

import re

with open(filename) as f:
    s = f.read()
with open(filename, 'w') as f:
    s = re.sub(y, z, s)
    f.write(s)
Run Code Online (Sandbox Code Playgroud)