python - 在 python 中创建和使用首选项文件

标签 python variables settings

对于堆栈和Python来说是全新的;希望比我更聪明的人可以提供帮助。我已经上下搜索,似乎找不到这个问题的实际答案,如果有确切的答案,我很抱歉,但我错过了:((我找到的几个要么是旧的,要么似乎不是工作)。

我发现的最接近的是 Best way to retrieve variable values from a text file? 唉,imp 似乎被贬值了,并尝试找出 importlib,但在我当前的大脑之上几乎没有弄清楚如何适应它,因为错误在我身上左右抛出。 这非常接近我想要的,如果有人可以帮助使用新方法进行更新,则可能会起作用,可惜仍然不知道如何覆盖旧变量。

= - - 场景 - - =

我想创建一个首选项文件(我们称之为settings.txt或settings.py:不需要与其他语言交叉兼容,但出于某种原因我更喜欢txt - 任何首选项/标准编码器可以传授吗?)。

\\\ settings.txt\
water_type = "Fresh"\
measurement = "Metric"\
colour = "Blue"\
location = "Bottom"\
...

我正在创建一个脚本 main_menu.py ,它将读取 settings.txt 中的变量,并在更改“保存”时写入此文件

即。 “选择水类型:”

  1. 新鲜

如果water_type与settings.txt相同,则不执行任何操作, 如果water_type不同,则覆盖settings.txt文件中的变量

该行的其他脚本也将读取和写入此设置文件。

我见过:

from settings import *

如果我进入 settings.py 路径,这似乎可以用于读取文件,但仍然让我不知道如何覆盖它。

也对你们能想到的任何更好/标准/想法持开放态度。

感谢对此的任何帮助!

最佳答案

以下是一些可能对您有帮助的建议:

  • 使用 json 文件:

设置.json

{
  "water_type": "Fresh",
  "measurement": "Metric",
  "colour": "Blue",
  "location": "Bottom",
...
}

然后在Python中:

import json

# Load data from the json file
with open("settings.json", "r") as f:
    x = json.load(f) # x is a python dictionary in this case

# Change water_type in x
x["water_type"] = "Salt"

# Save changes
with open("settings.json", "w") as f:
    json.dump(x, f, indent=4)
  • 使用 yaml 文件:(编辑:您需要安装 pyyaml)

设置.yaml

water_type: Fresh
measurement: Metric
colour: Blue
location: Bottom
...

然后在Python中:

import yaml

# Load data from the yaml file
with open("settings.yaml", "r") as f:
    x = yaml.load(f, Loader=yaml.FullLoader) # x is a python dictionary in this case

# Change water_type in x
x["water_type"] = "Salt"

# Save changes
with open("settings.yaml", "w") as f:
    yaml.dump(x, f)
  • 使用 INI 文件:

设置.ini

[Preferences]
water_type=Fresh
measurement=Metric
colour=Blue
location=Bottom
...

然后在Python中:

import configparser

# Load data from the ini file
config = configparser.ConfigParser()
config.read('settings.ini')

# Change water_type in config
config["Preferences"]["water_type"] = "Salt"

# Save changes
with open("settings.ini", "w") as f:
    config.write(f)

关于python - 在 python 中创建和使用首选项文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64179035/

相关文章:

javascript - var questionsRight 不是添加正确答案

c# - 如何以编程方式更改我的 Windows 桌面墙纸?

python - 从 python 中的特定标记中提取 URL

python - 使用带有 Excel 附件的 Python 发送电子邮件

python - 使用openpyxl用颜色填充单元格?

python - 从 settings.py 文件中提取密码

java - 如何在旧的 Android API 上强制执行操作栏设置图标

python - 如何使用 BeautifulSoup 停止文章打印两次

Python 字典未在不同文件之间更新

java - java中的final、const和static变量有什么区别