I’m trying a find a smooth way to read that file like "json" in python but it’s kinda weird (I tried to convert it but not possible
return {
["gradient"] = true,
["dark"] = true,
["sky"] = false,
["rainbow"] = false,
["settings"] = {
["size"] = 100,
["smooth"] = true,
["dev"] = {
["inspect"] = "F1"
}
["logo_size"] = 600
},
["jokes"] = false,
}
`
tried to make that code but receiving all time errors and not manage to read it
import ast
with open('file.ini') as f:
data_str = f.read()
data_str = data_str.replace('["', '"') .replace('"]', '"').replace("return ", "").replace("=", ":")
data = ast.literal_eval(data_str)
true_values = []
for k, v in data.items():
if v == True:
true_values.append(k)
print(true_values)
>Solution :
You can use a recursive function:
def parse(iterator, data):
# Use a `iterator` to read each line on demand
while True:
try:
line = next(iterator)
except StopIteration:
return
line = line.strip()
line = line.rstrip(',')
# The end of a dict, end the parsing here
if line == '}':
return
# Ignore lines that aren't key-value pairs
if ' = ' not in line:
continue
# Split the key-value pairs into two tokens
ltoken, rtoken = line.split(' = ')
# Remove the leading and trailing `["` from the keys
key = ltoken[2:-2]
# If it's the start of a nested sub-dictionary,
if rtoken == '{':
# Call the function again with the same iterator
subdata = {}
parse(iterator, subdata)
data[key] = subdata
else:
# Else, use the same dictionary
data[key] = rtoken
Usage:
t = """{
["gradient"] = true,
["dark"] = true,
["sky"] = false,
["rainbow"] = false,
["settings"] = {
["size"] = 100,
["smooth"] = true,
["dev"] = {
["inspect"] = "F1"
}
["logo_size"] = 600
},
["jokes"] = false,
}"""
import pprint
data = {}
parse(iter(t.split('\n')), data)
pprint.pprint(data)
It outputs
{'dark': 'true',
'gradient': 'true',
'jokes': 'false',
'rainbow': 'false',
'settings': {'dev': {'inspect': '"F1"'},
'logo_size': '600',
'size': '100',
'smooth': 'true'},
'sky': 'false'}