如何打开文本文件并找到特定的字符串值?

How can I open a Text file and find a specific strings value?

我在 Win32 平台上使用 Python 3.4。我想打开一个名为 somesettings.ini 的文件(只是一个文本文件)并搜索它,直到找到特定行的值。具体来说,我只想提取 Minimum Free Space= 行的当前设置(请参阅下面 somesettings.ini 的内容)并将其保存在字符串中以供代码中的其他地方使用。在下面显示的 ini 文件示例中,我想要结束的字符串是 32000.

提前致谢!

[Settings]
Idle Restart Time=300000
Minimum Free Space=32000
Max Record Time=1800
Deactive VR Timer=1800000
Use ERS=1
szaStorageDirectory=D:\
szaExportDirectory=Removable
szaConfigFile=C:\StreamsDefault.sdc
Enable LED=1
LED Port Address=3814
LED On Value=12
LED Off Value=4
LED Time Off=5900
LED Time On=100
Topmost Window=1
Grace Period=10000
Use Fast File Switching=1

你想为此使用 configparser

>>> import configparser
>>> config = configparser.ConfigParser()
>>> config.read(r'somesettings.ini')
>>> config['Settings']['Minimum Free Space']
32000

您可以通过这种方式访问​​ [Settings] 部分中的任何设置。

此时32000是一个字符串。如果您希望稍后在应用程序中使用 int,则需要将其转换为 int

>>> int(config['Settings']['Minimum Free Space'])

此代码适用于 python 2.7:

f=open("somesettings.ini", "r")
for l in f.readlines():
    If "Minimum Free Space" in l:
        index=l.find('=')
        res=l[index+1:]
        break
f.close()