![](/img/trans.png)
[英]Reading a configuration file in Python (storing/reading nested data with ConfigParser)
[英]Python / configparser file data reading
我在從文件中讀取數據時遇到了一些問題。 我想通過 function 從.ini數據文件中獲取屬性,但configparser無法正確讀取它。 如果有人能解釋這是錯誤的,我將不勝感激。 先感謝您!
Function 片段
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)
my.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
function 在您給它一個字符串數據類型時,在 filetypes 參數中需要一個元組。
正如 Nirmal Dey 指出的那樣, ConfigParser
只會返回字符串值。 您必須使用例如ast.literal_eval
將它們轉換為 Python 類型
FWIW,我寫了一個名為configdot 的小 package用於解析 INI 文件。 它將自動返回 Python 類型,並且還允許對配置變量進行屬性樣式訪問(例如config.select.ft
在您的情況下)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.