我有一个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发布于 2021-03-31 08:25:35
以不正确的模式"w":write-only打开tempfile.TemporaryFile。错误输出清楚地表明了这一点,因为第15行上的唯一读操作是tmp.read()。您需要使用mode="r+"打开tmp才能进行读写。
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 documentation on file open mode。
https://stackoverflow.com/questions/66879695
复制相似问题