Reputation: 335
I have a file I was playing around with to see if I can import it and convert it to a Python dictionary.
It is the default pyenv.cfg
file in venv
. It reads:
home = C:\Users\nope\AppData\Local\Continuum\anaconda3
include-system-site-packages = false
version = 3.6.4
I tried using:
with open(file, mode='r', encoding='utf-8') as f:
new_f = f.read().replace('=', ':')
d = dict(new_f)
This tells me I don't have enough arguments for dict(). It expects 2. I'm familiar with using dict(zip(list_1, list_2))
to create a dictionary. I'm not familiar with opening a file and creating one.
I'm looking for a very simply way to do this. I did some research with re
and it isn't turning out. Withing the with
block, I ran a = f.read().replace(' = ', '\',\'')
which returns:
home','C:\Users\nope\AppData\Local\Continuum\anaconda3
include-system-site-packages','false
version','3.6.4
Now I need to add a '
at the beginning and end of each line. Then I think I can use f.readlines()
to create a list I can slice into keys and values. I know how to do this with vim
or sed
in Linux, but I'm trying to stay within Python.
Please help. Thank you!
Upvotes: 0
Views: 2429
Reputation: 6526
I can suggest you an alternative one-line style solution using dict comprehension:
with open('pyenv.cfg') as f:
d = {k:v for line in f for k,v in [line.strip().split(' = ')]}
print(d)
# {'home': 'C:\\Users\\nope\\AppData\\Local\\Continuum\\anaconda3',
# 'include-system-site-packages': 'false',
# 'version': '3.6.4'}
Upvotes: 1
Reputation: 44354
Just treat it as normal data, don't try to convert it to python or you will end-up going down the horrible eval
road.
d = {}
file = 'pyenv.cfg'
with open(file) as f:
for line in f:
k, v = line.rstrip().split(' = ')
d[k] = v
import pprint
pprint.pprint(d)
Gives:
{'home': 'C:\\Users\\nope\\AppData\\Local\\Continuum\\anaconda3',
'include-system-site-packages': 'false',
'version': '3.6.4'}
Upvotes: 0
Reputation: 28370
I would suggest taking a look at the builtin configparser library which will return a dictionary like object.
Alternatively you can simply split the lines on =
my_dict = {}
for line in open(file_path).readlines():
key, val = line.strip().split('=') # Remove \n and split on =
my_dict[key.strip()] = val.strip() # Remove trailing leading spaces use
# Note that vals will all be strings you may need to convert type for some
Upvotes: 2