简体   繁体   English

逐行修改 json 文件会出现错误 UnsupportedOperation: not readable

[英]Amending json file line by line gives error UnsupportedOperation: not readable

I have a json file that I want to update line by line but I am getting the error UnsupportedOperation: not readable when I try to run the function below.我有一个 json 文件,我想逐行更新,但是当我尝试运行下面的 function 时出现错误 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())
                

the function used for updating the line is:用于更新行的 function 是:

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)
   

exception code异常代码

---------------------------------------------------------------------------
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

The tempfile.TemporaryFile is opened with the incorrect mode, "w" : write-only. tempfile.TemporaryFile以不正确的模式打开, "w" :只写。 The error output makes this clear since the only read operation on line 15 is tmp.read() .错误 output 清楚地说明了这一点,因为第 15 行的唯一读取操作是tmp.read() You need to open tmp with mode="r+" in order to read and write.您需要使用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 modes. Python 关于文件打开模式的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM