python - 读取 "variable=value"(Windows INI) 格式的文件?

标签 python file

我正在学习 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/

相关文章:

python - 从电子邮件正文中提取域名

c++ - 我是否已成功从堆中删除指针?

android - 致命异常:找不到音频记录器线程和文件异常

asp.net - 将 ExcelPackage 文件发送给用户

android - 保存并读取图像,但是打开文件夹时找不到

Python事件没有Key属性

python - 最佳实践 : update/extend subclass class attribute

python - ffmpeg 出错,错误代码为 : -5

python - db.StringListProperty 的 App Engine NDB 替代方案

java - 如何有效地跟踪 Java 中大文件的更改(以及最重要的读取)