python-3.x - 我需要一种最简单的方法来使用 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)
解决方案
将整个文件读入内存,进行所需的更改,然后将这些更改写入同一个文件。
因此,一段基本的代码可以满足您的要求:
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
推荐阅读
- python - 当 Python 次要版本更改时,Anaconda 如何处理 pip 安装的包和其他自定义?
- javascript - 使用 google API 和 javascript - 如何包含请求正文
- javascript - 如何制作包含多个图像的 JS 幻灯片?
- python - 通过 python3 套接字发送列表
- cluster-analysis - 任何推荐引擎,“建议主题”块的技术?
- javascript - 所有变量的JavaScript类型数组?
- javascript - 我的汉堡菜单在特定页面上没有响应?
- sudoers - 允许从 nis 共享的组使用 sudo
- sql - Presto sql“值不能转换为时间戳”
- react-native-maps - 不能使用 MapView 组件中的 animateCamera 方法