Tomee
Tomee

Reputation: 139

Python / configparser file data reading

I'm having some problems with reading data from file. I want to get properties from .ini data file to be red by the function, but configparser doesn't read it properly. I would be very grateful if someone could explain that is wrong. Thank you in advance!

Function snippet

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 file data

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

Upvotes: 0

Views: 985

Answers (2)

Jussi Nurminen
Jussi Nurminen

Reputation: 2408

As Nirmal Dey pointed out, ConfigParser will only return string values. You'd have to convert them to Python types using e.g. ast.literal_eval

FWIW, I have written a small package called configdot for parsing INI files. It will automatically return Python types and also allows attribute-style access for config variables (e.g. config.select.ft in your case)

Upvotes: 1

Nirmal Dey
Nirmal Dey

Reputation: 189

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

Every key-value pair present in the .ini file would be parsed as a string.

Your filedialog.askopenfilename the function expects a tuple in the filetypes argument while you are giving it a string datatype.

Upvotes: 1

Related Questions