首页 > 解决方案 > 逐行修改 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

标签: pythonjson

解决方案


以不正确的tempfile.TemporaryFile模式打开,"w":只写。错误输出清楚地说明了这一点,因为第 15 行上唯一的读取操作是tmp.read(). 您需要打开tmpwithmode="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文档。


推荐阅读