首页 > 解决方案 > 在 jupyter notebook Watson IBM Studio 中加载和读取 JSON 文件的文件未找到错误

问题描述

我正在研究 IBM 云 Watson Studion 环境。我编写了这个脚本来获取挪威每个城市的更新人口。JSON 文件已上传到我的项目的资产中,我正在尝试调用并读取它,"with open"但出现错误:

FileNotFoundError: [Errno 2] No such file or directory: 'Folkemengde.json'

我也用过,但结果还是一样:

pd.read_json ('Folkemengde.json')

当 JSON 文件已经上传到资产中时,如何获取它的路径?或者它是否像 JSON 文件一样工作或无关紧要?

我的剧本

population_data = {}
with open("Folkemengde.json", "r", encoding="utf-8") as inp:
        data = json.load(inp)
        kommuns_index = data["dataset"]["dimension"]["Region"]["category"]["index"]
        kommuns_label = data["dataset"]["dimension"]["Region"]["category"]["label"]
        values = data["dataset"]["value"]
        for i, municipality_code_str in enumerate(kommuns_index.keys()):
            k = municipality_code_str[2:]
            if k == "Rest":
                continue
            municipality_name = kommuns_label[municipality_code_str]
            population = values[i]
            population_data[int(k)] = population
            
    def from_municipality_pop(row):
        global population_data
        if row['from_municipality_code'] == 0:
            return 0
        return population_data[row['from_municipality_code']]
    df['population'] = df.apply(lambda row: from_municipality_pop(row), axis=1)

标签: pythonjsonibm-watson

解决方案


我在https://medium.com/@snehalgawas/working-with-ibm-cloud-object-storage-in-python-fe0ba8667d5f的帮助下找到了答案:

要访问 IBM Cloud Object Storage,您需要通过打开笔记本并单击来插入的凭证Find and Add Data,然后单击insert credentials。它会给出如下所示的内容:

# @hidden_cell
# The following code contains the credentials for a file in your IBM Cloud Object Storage.
# You might want to remove those credentials before you share your notebook.
credentials = {
    'IBM_API_KEY_ID': '*******************************',
    'IAM_SERVICE_ID': '*******************************',
    'ENDPOINT': '*******************************',
    'IBM_AUTH_ENDPOINT': '*******************************',
    'BUCKET': '*******************************',
    'FILE': '*******************************'
}

然后使用这些凭据创建一个低级客户端,例如:

from ibm_botocore.client import Config
import ibm_boto3
cos = ibm_boto3.client(service_name='s3',
    ibm_api_key_id=credentials['IBM_API_KEY_ID'],
    ibm_service_instance_id=credentials['IAM_SERVICE_ID'],
    ibm_auth_endpoint=credentials['IBM_AUTH_ENDPOINT'],
    config=Config(signature_version='oauth'),
    endpoint_url=credentials['ENDPOINT'])

然后使用客户端凭据将该文件作为对象获取:将文件作为对象获取并加载数据:

any_name = cos.get_object(Bucket= credentials['BUCKET'], Key='Your_file_name.json')['Body']
data = json.load(any_name)

推荐阅读