简体   繁体   中英

'str' object has no attribute 'write'

Getting the infamous 'str' object has no attribute 'write' . Here I can't tell why python thinks my file object out_file is a string. Probably something else I'm missing. The error is flagged on the commented line.

PS this code is for printing a more reader friendly version of an arbitrary json.

import json
import os
json_path = os.path.normpath(r"my_dir")

#---------------------------------------------------------------------
def json_break(data, tab_str, out_file):
    k_str = tab_str
    if type(data) is list:
        i = 0
        for i in range(len(data)):
            json_break(data[i], tab_str + '  ', str(data[i]))
            i += 1
    elif type(data) is dict:
        for k in data:
            if type(data[k]) is str:
                k_str += k + ': ' + data[k]
                out_file.write(k_str)
            else:
                k_str += k + ':\n'
                out_file.write(k_str)  # 'str' object has no attribute 'write'
                json_break(data[k], tab_str + ' ', out_file)
    return None
#---------------------------------------------------------------------

with open(os.path.join(json_path,'my_json.json')) as in_file:
    data = json.load(in_file)

out_file = open(os.path.join(json_path,'print_json.txt'),"w") 

tab_str = ' '
json_break(data, tab_str, out_file)

out_file.close()

json_break() accepts last arg as a file object. Replace

json_break(data[i], tab_str + '  ', str(data[i]))

With

json_break(data[i], tab_str + '  ', out_file)

And it should work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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