【问题标题】:How to read file content from the relative path in config file如何从配置文件中的相对路径读取文件内容
【发布时间】:2020-12-11 08:33:22
【问题描述】:

我有一个配置文件,其中 data_2 内容是巨大的 JSON 对象,所以我提到了文件的相对路径:

    Test.ini

    [COMMON]
    data_1 =Hello
    data_2 =c:/.../data.txt

如何在python中读取'data.txt'文件内容。

python 中的初始配置为:

   try:
      from configparser import ConfigParser
   except ImportError:
      from ConfigParser import ConfigParser  # ver. < 3.0
   config = ConfigParser()
   config.read('test.ini')

  for x in range(1,6):
      data = config.get('COMMON', f'data_{x}')
      print(data)

用于打印操作:

     data_1 = Hello  # get printed
     data_2 = c:/.../data.txt # get printed instaed of data.txt file content.

【问题讨论】:

    标签: python python-3.x configuration relative-path


    【解决方案1】:

    您需要打开文件并阅读它(如果是 JSON,甚至需要解析它):

    import json
    
    # ...
    
    # First retrieve the value in the config then
    
    # ...
    
    with open(data_2, "r") as f:
      json_data = json.load(f)
    
    # ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-07
      • 1970-01-01
      • 2013-11-21
      • 2014-12-07
      • 1970-01-01
      • 2023-03-04
      相关资源
      最近更新 更多