首页 > 解决方案 > 我需要一种最简单的方法来使用 python 脚本更改文件的内容

问题描述

我有一个python文件“main.py”,里面有一些代码我需要一个简单的python函数来查找和替换其中的某一行代码。 示例:main.py 包含

@receiver(post_save, sender=User)
def index_user(sender, instance, **kwargs):
    if validate_checks(instance):
        index_model(instance)

我需要一个函数将上面的代码更改为

# @receiver(post_save, sender=User)
def index_user(sender, instance, **kwargs):
    if validate_checks(instance):
        index_model(instance)

标签: python-3.xfile

解决方案


将整个文件读入内存,进行所需的更改,然后将这些更改写入同一个文件。

因此,一段基本的代码可以满足您的要求:

def replace_and_write(fn: str, exact_match: str, replacement: str) -> None:
    with open(fn, "r") as f_in:
        contents = f_in.read()

    with open(fn, "w") as f_out:
        f_out.write(contents.replace(exact_match, replacement))

replace_and_write("test.txt", "foo", "Hello, World!")

在一个看起来像这样的文件上运行它:

foo
bar
baz

将其更改为:

Hello, World!
bar
baz

推荐阅读