正确阅读 settings.ini
Reading settings.ini correctly
例如,我的程序有一个 settings.ini 文件,其中包括:
theme=white
SaveDirectory=C:\Screenshots
我是这样读的:
with open("settings.ini", "r") as settings:
setting = settings.readlines()
theme = setting[0]
theme = theme[len("theme="):].strip()
bg = theme
print(theme)
SaveDirectory = setting[1]
SaveDirectory = SaveDirectory[len("SaveDirectory="):].strip()
print(SaveDirectory)
settings.close()
但我知道,当我的 .ini 文件变长时,这很糟糕且有风险。我需要一个函数来读取行的开头。喜欢:function("theme=")
。 python3 有类似的东西吗?
Python 3 有一个 configparser module which does exactly what you want, though you'll need to add a [section]
header to the top of your file first so that it conforms to the supported file structure.
例如,我的程序有一个 settings.ini 文件,其中包括:
theme=white
SaveDirectory=C:\Screenshots
我是这样读的:
with open("settings.ini", "r") as settings:
setting = settings.readlines()
theme = setting[0]
theme = theme[len("theme="):].strip()
bg = theme
print(theme)
SaveDirectory = setting[1]
SaveDirectory = SaveDirectory[len("SaveDirectory="):].strip()
print(SaveDirectory)
settings.close()
但我知道,当我的 .ini 文件变长时,这很糟糕且有风险。我需要一个函数来读取行的开头。喜欢:function("theme=")
。 python3 有类似的东西吗?
Python 3 有一个 configparser module which does exactly what you want, though you'll need to add a [section]
header to the top of your file first so that it conforms to the supported file structure.