python - 使用带引号的字符串的 json.dumps 在 Python 中的 sed 命令不保留单引号
问题描述
对不起,如果标题有点复杂......一个例子会更好地说明我的意思:
我有一个名为 foo 的文本文件,其中包含字符串“bar”。
在 Python 中,我有一本字典:
d = {"key": "item['id']"}
我想用我的字典的 json 转储替换文件中的字符串 bar。命令:
import subprocess
subprocess.call("sed 's#bar#%s#g' foo > foo2" % json.dumps(d),shell=True)
当我 cat 文件 foo2 时,结果是:
> cat foo2
{"key": "item[id]"}
问题是:单引号在 id 周围丢失。我怎样才能避免这种情况?
解决方案
正如@Shawn 所建议的那样,我使用基于 re.sub 的“python sed”函数在 Python 中完成了这一切:
def psed(foo,bar,source,dest):
"""
implements a python sed, substituting (with multi-line mode) foo for bar
in file source, writing the result in file dest
"""
with open(source,'r') as f:
content = f.read()
f.close()
content_new = re.sub(foo,bar,content,flags=re.M)
with open(dest,'w') as f:
f.write(content_new)
f.close()
推荐阅读
- google-cloud-platform - Google Cloud Datalab 和 Cloud Shell 访问问题
- python - 使用查询检查关系是否存在
- php - Echoing returned value from previous function
- vue.js - v-form 和 v-text-field 在 vue cli 3.0 中不起作用
- html - AngularJS - 将变量插入脚本属性
- c++ - 如何将 cv::Mat & Img 复制到 unsigned char* img?opencv
- javascript - 发送多笔交易,但一笔总是失败
- xamarin.android - 如何从默认主题更改为其他主题Theme.Material.Light
- node.js - 将 dotenv 与捆绑的客户端代码一起使用
- python - 使用 Python 将数据填充到现有的 excel 文件中