Parse key value pairs in a text file

后端 未结 6 1313
無奈伤痛
無奈伤痛 2020-11-28 09:31

I am a newbie with Python and I search how to parse a .txt file. My .txt file is a namelist with computation informations like :

myfile.txt

6条回答
  •  伪装坚强ぢ
    2020-11-28 10:00

    Use pandas.read_csv when the file format becomes more fancy (like comments).

    val = u'''var0 = 16
    var1 = 1.12434E10
    var2 = -1.923E-3
    var3 = 920'''
    print(pandas.read_csv(StringIO(val), # or read_csv('myfile.txt',
                delimiter='\s*=\s*',
                header=None,
                names=['key','value'],
                dtype=dict(key=numpy.object,value=numpy.object), # or numpy.float64
                index_col=['key']).to_dict()['value'])
    # prints {u'var1': u'1.12434E10', u'var0': u'16', u'var3': u'920', u'var2': u'-1.923E-3'}
    

提交回复
热议问题