如何修复“ str”对象没有属性“ read”错误

问题描述 投票:-1回答:1

我正在测试一个应该将json转换为纯文本的函数。

我已经检查了类似的线程,但是我发现最相关的是它们的实际功能有问题。对于这个问题,我一点都不满意json或Python,但是我的猜测是问题出在我如何使用函数而不是实际函数上。

我创建并尝试转换的json文件如下:

person = {}

person ['Name'] = {
    'name': 'Name',
    'adress': 'Somewhere',
    'phone_no': '0700000000',
    'email_id': None
}

这是我正在测试的功能:

def json_to_plaintext(json_file, attribute):
    json_tmp = json.loads(json_file.read())
    attr = json_tmp[attribute]  # collect attribute
    txt_file = open("json_attribute.txt", "w+")
    attr = str(attr)  # make string of object
    txt_file.write(attr)
    txt_file.close()

return txt_file

为了测试我运行

plain_text.json_to_plaintext(r'C:\Desktop\Tests\test2', 'person')

“ test2”是我创建的json文件,'person'是我认为的属性。

运行此文件时出现错误:

json_tmp = json.loads(json_file.read())
AttributeError: 'str' object has no attribute 'read'
python json plaintext
1个回答
1
投票

json_file是文件名,而不是文件。您需要打开文件才能读取它。

您也可以使用json.load()代替json.loads()。它将从文件本身读取。

def json_to_plaintext(filename, attribute):
    with open(filename) as json_file:
        json_tmp = json.load(json_file)
    attr = json_tmp[attribute]  # collect attribute
    with open("json_attribute.txt", "w+") as txt_file:
        attr = str(attr)  # make string of object
        txt_file.write(attr)

但是,您显示的文件不是正确的JSON文件。 JSON文件应如下所示:

{ "person": {
    "name": "Name",
    "adress": "Somewhere",
    "phone_no": "0700000000",
    "email_id": null
    }
}

您显示的是一个Python脚本,该脚本定义了一个名为person的变量。如果要读取和执行另一个脚本,可以使用import

© www.soinside.com 2019 - 2024. All rights reserved.