我正在学习 Python,作为初学者,我几乎没有问题。
我需要读取具有这种格式的文件:
# This is the text file
[label1]
method=auto
[label2]
variable1=value1
variable2=ae56d491-3847-4185-97a0-36063d53ff2c
variable3=value3
现在我有以下代码:
# This is the Python file
arq = open('desiredFile').read()
index = arq.rfind('variable1=')
(??)
但我真的不知道该如何继续下去。我的目标是读取值直到出现新行。我想计算“id=”和新行之间的索引,所以在这个索引中获取文本,但我不知道如何在 Python 中执行此操作。总结我想将 [label2] 的值存储在 Python 变量中:
pythonVariable1 = <value of variable1 in [label2]>
pythonVariable2 = <value of variable2 in [label2]>
pythobVariable3 = <value of variable3 in [label2]>
请注意,pythonVariable2 等于“ae56d491-3847-4185-97a0-36063d53ff2c”,文本文件中的变量具有唯一的名称。那么,如何将这个变量的值存储在 Python 变量中呢?
最佳答案
使用 configparser
module来处理这个。该模块直接解析此文件格式(称为 Windows INI 格式)。
try:
# Python 3
from configparser import ConfigParser
except ImportError:
# Python 2
from ConfigParser import ConfigParser
config = ConfigParser()
config.readfp( open( 'desiredFile' ) )
somevar = config.get( 'label2', 'variable1' )
关于python - 读取 "variable=value"(Windows INI) 格式的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19351262/