Search code examples
python-3.xurllib2

fetch data from .txt web file (as key,value set) into dictionary


I need to download content of .txt file from web, separate each key,value set and insert them into dictionary.

Here is txt file where are my parameters which have to be placed in dict-> http://mign.pl/ver.txt

and dict should looks like this: dic = {"Version": 1.0, "Hires": False, "Temperature": 55, "Description": "some description"}

I have already used urllib2 to download content:

import urllib.request as urllib2 
url = urllib2.urlopen('http://www.mign.pl/ver.txt')

What next?


Solution

  • You can use built-in configparser module to parse the values (doc):

    import configparser
    import urllib.request as urllib2
    
    data = urllib2.urlopen('http://www.mign.pl/ver.txt')
    
    c = configparser.ConfigParser()
    c.read_string('[root]\n' + data.read().decode('utf-8'))
    print({k:v for k, v in zip(c['root'], c['root'].values())})
    

    Prints:

    {'version': '1.0', 'hires': 'False', 'temperature': '55', 'description': 'Some description'}
    

    Or just work with connfigparser directly (e.g. print(c['root']['version']) will print 1.0)