Parse key value pairs in a text file

后端 未结 6 1286
無奈伤痛
無奈伤痛 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 09:52

    As @kev suggests, the configparser module is the way to go.

    However in some scenarios (a bit ugly, I admit) but very simple and effective way to do to this is to rename myfile.txt to myfile.py and do a from myfile import * (after you fix the typo var 0 -> var0)

    However, this is very insecure, so if the file is from an external source or can be written by a malicious attacker, use something that validates the data instead of executing it blindly.

提交回复
热议问题