为什么当我使用 json.load() 方法时,Python3 不精细位于同一目录中的

我正在学习Python3,并且我正在尝试通过从JSON文件启动其属性来创建对象代理(自定义对象)。


问题是,当我启动python文件时,它找不到该文件,该文件位于同一目录中。我检查了名字,没有错别字。我不明白问题到底出在哪里。


这是我的文件夹结构:


project/

    model.py

    agents-100k.json

这是我的文件model.py


import json



class Agent:

    def __init__(self, **agent_attributes):

        """Constructor of Agent class"""


        # Print each element of dict

        print(agent_attributes.items())


        # Get the name and the value of each entry in dict

        for attr_name, attr_value in agent_attributes.items():

            # setattr(instance, attribute_name, attribute_value)

            setattr(self, attr_name, attr_value)


    def say_hello(self, first_name):

        """Say hello to name given in argument"""


        return "Hello " + first_name + "!"



def main():

    for agent_attributes in json.load(open("agents-100k.json")):

        agent = Agent(**agent_attributes)

        print(agent.agreeableness)


main()

下面是该文件的示例(有很多条目,因此我将只显示其中的两个条目):agents-100k.json


[

  {

    "age": 84,

    "agreeableness": -0.8437190198916452,

    "conscientiousness": 0.6271643010309115,

    "country_name": "China",

    "country_tld": "cn",

    "date_of_birth": "1933-12-27",

    "extraversion": 0.3229563709288293,

    "id": 227417393,

    "id_str": "bNn-9Gc",

    "income": 9881,

    "internet": false,

    "language": "Standard Chinese or Mandarin",

    "latitude": 33.15219798270325,

    "longitude": 100.85840672174572,

    "neuroticism": 0.15407262417068612,

    "openness": 0.041970542572878806,

    "religion": "unaffiliated",

    "sex": "Male"

  },

 

无论如何,感谢您的帮助。


qq_花开花谢_0
浏览 109回答 1
1回答

繁星点点滴滴

Python 打开相对于脚本执行位置的文件。因此,如果使用项目/模型运行文件.py json 应位于项目文件夹之外。如果 json 始终包含在与 python 文件相同的文件夹中,则可以使用以下代码打开该文件:import jsonimport ospath = os.path.dirname(os.path.abspath(__file__))import jsodef main():    for agent_attributes in json.load(open(os.path.join(path, "agents-100k.json")):        agent = Agent(**agent_attributes)        print(agent.agreeableness)main()这个问题给出了关于它如何工作的更详细的解释。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python