簡體   English   中英

Python/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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM