我正在學習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()
這個問題給出了關于它如何工作的更詳細的解釋。
添加回答
舉報
0/150
提交
取消