为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

qq_花开花谢_0 2022-09-20 16:40:59
我正在学习Python3,并且我正在尝试通过从JSON文件启动其属性来创建对象代理(自定义对象)。问题是,当我启动python文件时,它找不到该文件,该文件位于同一目录中。我检查了名字,没有错别字。我不明白问题到底出在哪里。这是我的文件夹结构:project/    model.py    agents-100k.json这是我的文件model.pyimport jsonclass 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"  }, 无论如何,感谢您的帮助。
查看完整描述

1 回答

?
繁星点点滴滴

TA贡献1803条经验 获得超3个赞

Python 打开相对于脚本执行位置的文件。因此,如果使用项目/模型运行文件.py json 应位于项目文件夹之外。


如果 json 始终包含在与 python 文件相同的文件夹中,则可以使用以下代码打开该文件:


import json

import os


path = os.path.dirname(os.path.abspath(__file__))

import jso



def main():

    for agent_attributes in json.load(open(os.path.join(path, "agents-100k.json")):

        agent = Agent(**agent_attributes)

        print(agent.agreeableness)


main()

这个问题给出了关于它如何工作的更详细的解释。


查看完整回答
反对 回复 2022-09-20
  • 1 回答
  • 0 关注
  • 80 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号