Qt/Python中配置文件的存储及读取

使用QSettings

QT中推荐使用这种方式

1
2
3
4
5
6
7
8
9
10
from PySide2.QtCore import QSettings

zsetting = QSettings("z_scanner_config.ini", QSettings.IniFormat)

def save_config(key,value):
zsetting.setValue(key,value);


def get_config(key):
return zsetting.value(key,"")

使用

1
2
3
4
from utils.z_setting import save_config,get_config

save_config("name","张三")
print("name:"+get_config("name"))

配置存储位置:当前的工作目录内

可以通过以下方式获取

1
2
3
4
5
import os

# 获取当前工作目录
current_directory = os.getcwd()
print("当前工作目录:", current_directory)

使用configparser

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import configparser

config = configparser.ConfigParser()
config_name = "z_scanner_config.ini"

def save_config(key,value):
config.read(config_name)
config["Common"][key] = value
with open(config_name, "w") as f:
config.write(f)


def get_config(key):
config.read(config_name)
return config["Common"][key]

使用

1
2
3
4
from utils.z_setting import save_config,get_config

save_config("name","张三")
print("name:"+get_config("name"))

使用JSON

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import json
import os

config_name = "z_scanner_config.json"
is_load = False

config = {

}

def load_config():
global config
if os.path.exists(config_name):
with open(config_name, "r") as f:
try:
config = json.load(f)
except:
config = {}
else:
config = {}


def save_config(key,value):
if not is_load:
load_config()
config[key] = value
with open(config_name, "w") as f:
json.dump(config, f)


def get_config(key):
if not is_load:
load_config()
return config[key]

使用

1
2
3
4
from utils.z_setting import save_config,get_config

save_config("name","张三")
print("name:"+get_config("name"))