Python/configparser文件数据读取

Python / configparser file data reading

我在从文件中读取数据时遇到一些问题。我想通过函数从 .ini 数据文件中获取属性,但 configparser 无法正确读取它。如果有人能解释这是错误的,我将不胜感激。提前致谢!

函数片段

config = configparser.ConfigParser()
config.read('config.ini')

def browseFiles():
    filename = filedialog.askopenfilename(initialdir = config['select']['dir'],
                                          title = config['select']['ttl'],
                                          filetypes = config['select']['ft'])
      
    # Change label contents
    label_file_explorer.configure(text="File Opened: "+filename)

我的 .ini 文件数据

[select]
#directory
dir = "home/"
#title
ttl = "Select a File"
#filetype
ft = (("Text files","*.txt*"),("all files","*.*"))
  

Config parsers do not guess datatypes of values in configuration files, always storing them internally as strings.

.ini 文件中存在的每个键值对都将被解析为字符串。

你的 filedialog.askopenfilename 函数在你给它一个字符串数据类型时需要文件类型参数中的一个元组。

正如 Nirmal Dey 指出的那样,ConfigParser 只会 return 字符串值。您必须使用例如将它们转换为 Python 类型ast.literal_eval

FWIW,我写了一个名为 configdot 的小包来解析 INI 文件。它会自动 return Python 类型并且还允许配置变量的属性样式访问(例如 config.select.ft 在你的情况下)