【问题标题】:Reading file with python用python读取文件
【发布时间】:2020-11-25 00:40:35
【问题描述】:

这是我读取 json 文件的代码。但即使 json 文件在同一个地方,比如 python 文件,它也不起作用。错误是'没有这样的文件或目录:'agents-100k.json'你能帮帮我吗

import json
class Agent:
    def __init__(self, **agent_attributes):
        for attr_name, attr_value in agent_attributes.items():
            setattr(self, attr_name, attr_value)

def main():
    for agent_attributes in json.load(open("agents-100k.json")):
        agent = Agent(**agent_attributes)
        print(agent.agreeableness)

main()

【问题讨论】:

  • 使用文件的绝对路径而不依赖于相对路径?

标签: python json file


【解决方案1】:

你好,最好使用绝对路径,因为上面的 cmets 在这里举了一个例子

import json
f = open(r'the path of the json file')
class Agent:
    def __init__(self, **agent_attributes):
        for attr_name, attr_value in agent_attributes.items():
            setattr(self, attr_name, attr_value)
def main():
    for agent_attributes in json.load(f):
        agent = Agent(**agent_attributes)
        print(agent.agreeableness)
main()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-12
    • 2018-03-04
    • 2020-12-24
    • 1970-01-01
    相关资源
    最近更新 更多