亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么當我使用 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 關注
  • 102 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號