我有一个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)
发布于 2020-02-24 02:39:26
将整个文件读入内存,进行所需的更改,然后将这些更改写入同一个文件。
因此,一段基本代码可以实现您想要的结果:
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
https://stackoverflow.com/questions/60372886
复制相似问题