【问题标题】:python program to store a specific string from a file and store it in a variablepython程序存储文件中的特定字符串并将其存储在变量中
【发布时间】:2018-07-01 23:02:25
【问题描述】:

我想从一个文件中存储一个特定的字符串,例如:-

【问题讨论】:

标签: python python-3.x python-2.7


【解决方案1】:

在我看来,您的文本格式是 json。在这种情况下,答案很简单:

import json

with open('file.txt') as f:
    data = json.loads(f.read())
    # access the required key
    my_variable = data['my_id']

【讨论】:

    【解决方案2】:

    首先

    在您的示例 json 文件中,您使用的引号不一致,选择 ' 或 " 并坚持下去。

    代码

    import json
    data = json.load(open("file.json"))
    # this is the variable you are after
    variable = data["my_id"]
    

    【讨论】:

      猜你喜欢
      • 2020-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-25
      相关资源
      最近更新 更多