0

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","*.*")) 

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

4 Comments

I love it @jussi, its very convenient
By the way where i need put st.literal_eval? In here filedialog.askopenfilename ?
You'd have to put it around the string-valued arguments. E.g. filetypes = ast.literal_eval(config['select']['ft'])
But if i use your package i don't need it right?
1

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.

2 Comments

@Dey Sorry, but I didn't understand correctly the last part
filetypes argument expects an iterator. It can not work with a stringified version of a tuple. if you wish to pass the filetype argument from your .ini file then you need to make a slight change in the .ini file. ``` ft[]=("Text Files", "*.txt") ft[]=(""all files ", ".") ``` after it, the config parser would know that ft is a list and not a single string.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.