Python - converting textfile contents into dictionary values/keys easily

前端 未结 3 585
耶瑟儿~
耶瑟儿~ 2020-12-20 17:19

Let\'s say I have a text file with the following:

line = \"this is line 1\"
line2 = \"this is the second line\"
line3 = \"here is another line\"
line4 = \"ye         


        
相关标签:
3条回答
  • 2020-12-20 18:07

    Here's what the urlopen version of inspectorG4dget's answer might look like:

    from urllib.request import urlopen
    url = 'https://raw.githubusercontent.com/sedeh/github.io/master/resources/states.txt'
    response = urlopen(url)
    lines = response.readlines()
    state_names_dict = {}
    for line in lines:
        state_code, state_name = line.decode().split(":")
        state_names_dict[state_code.strip()] = state_name.strip()
    
    0 讨论(0)
  • 2020-12-20 18:08
    f = open(filepath, 'r')
    answer = {}
    for line in f:
        k, v = line.strip().split('=')
        answer[k.strip()] = v.strip()
    
    f.close()
    

    Hope this helps

    0 讨论(0)
  • 2020-12-20 18:11

    In one line:

    d = dict((line.strip().split(' = ') for line in file(filename)))
    
    0 讨论(0)
提交回复
热议问题