python - 逐行修改 json 文件会出现错误 UnsupportedOperation: not readable
问题描述
我有一个 json 文件,我想逐行更新,但我收到错误 UnsupportedOperation: not readable 当我尝试运行下面的函数时。
def update_json(json_file):
with tempfile.TemporaryFile(mode ='w') as tmp:
with open(json_file) as f:
print(json_file)
for json_line in f:
data = json.loads(json_line)
if populate_tags(data, param):
tmp.write(json.dumps(data) + '\n')
tmp.seek(0)
with open(json_file, 'w') as f:
f.write(tmp.read())
用于更新行的函数是:
def populate_tags(data, param_values):
tags={}
for l in data['targets']:
item = l['item'].strip().lower()
text = l['text'].strip().lower()
d={'type': item, 'text_value': text}
key_value = str(d).strip().lower()
tag = param_values.get(key_value)
if tag is None:
continue
tag = str(tag).replace('"','')
tags[item] = tag
tags[item] = literal_eval(tags[label])
data['options'] = {'Tags': dict(tags)}
return bool(tags)
异常代码
---------------------------------------------------------------------------
UnsupportedOperation Traceback (most recent call last)
<ipython-input-65-b4c1e92652ac> in <module>
22
23 for filename in files:
---> 24 update_json(filename)
<ipython-input-65-b4c1e92652ac> in update_json(json_file)
13 tmp.seek(0)
14 with open(json_file, 'w') as f:
---> 15 f.write(tmp.read())
16
17
UnsupportedOperation: not readable
解决方案
以不正确的tempfile.TemporaryFile
模式打开,"w"
:只写。错误输出清楚地说明了这一点,因为第 15 行上唯一的读取操作是tmp.read()
. 您需要打开tmp
withmode="r+"
才能读取和写入。
def update_json(json_file):
with tempfile.TemporaryFile(mode ='r+') as tmp:
with open(json_file) as f:
print(json_file)
for json_line in f:
data = json.loads(json_line)
if populate_tags(data, param):
tmp.write(json.dumps(data) + '\n')
tmp.seek(0)
with open(json_file, 'w') as f:
f.write(tmp.read())
关于文件打开模式的Python文档。
推荐阅读
- python - 根据交叉点在列表中查找最佳超集
- angular - 使用 Leaflet 在 Angular 8 项目中缓存地图图块的最佳方法
- javascript - Next.js 和 Webpack 内联 Javascript 或 CSS 资源
- r - 如何在r中按名称对列表列表进行排序?
- c# - 列表中的空值
在多个线程中添加和删除时 - c# - 流利的断言 - 如何在类型检查后正确链接
- python - 为什么 np.savetxt 什么都不写?
- javascript - 我需要将我的菜单项从 href 更改为更具响应性的内容
- kdb - 比较两个表中的两个复合列
- spartacus-storefront - Spartacus 中可配置 URL 支持的字符