首先获取到需要读取文件的根目录
def get_project_dir():
"""
获取当前项目的根路径
:return: 返回根路径的绝对路径
"""
project_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../.."))
return project_dir
Yaml文件操作
class YamlConfig:
def __init__(self, yaml_file, folder="config"):
"""
初始化 YamlConfig 对象
:param folder: 配置文件所在文件夹名称
"""
self.logger = logger
self.file_path = Path(get_project_dir(), folder, yaml_file)
print(self.file_path)
def write_yaml(self, data: dict):
"""写入数据到yaml,但是会覆盖全部内容
"""
try:
with open(self.file_path, 'w', encoding="utf-8") as f:
yaml.safe_dump(data, f, allow_unicode=True)
self.logger.debug(f"yaml文件【{self.file_path}】写入数据成功!内容如下:\n{format_print(data)}")
return data
except FileNotFoundError:
self.logger.exception(f"写入{self.file_path}文件错误!")
def update_yaml(self, key: str, value: str):
"""仅更新yaml文件
"""
result = self.load_yaml()
# 更新部分内容
result = result.copy()
result[key] = value
try:
# 写入更新后的 YAML 文件
with open(self.file_path, 'w', encoding="utf-8") as f:
yaml.safe_dump(result, f)
except FileNotFoundError:
self.logger.exception(f"写入{self.file_path}文件错误!")
def load_yaml(self):
"""
读取 YAML 配置文件
:return: 配置数据字典
"""
try:
with open(self.file_path, 'r', encoding="utf-8") as f:
data = yaml.safe_load(f.read())
self.logger.debug(f"yaml文件【{self.file_path}】加载成功!内容如下:{format_print(data)}")
return data
except FileNotFoundError:
print(f"文件 {self.file_path} 不存在。")
return None
except Exception as e:
print(f"读取配置文件时发生错误:{e}")
return None
Json文件操作
class JsonConfig:
def __init__(self, json_file: str, folder: str = "config"):
"""初始化JsonConfig对象
Args:
json_file: json配置文件
folder: json配置文件的路径
"""
self.logger = logger
self.file_path = Path(get_project_dir(), folder, json_file)
print(self.file_path)
def read_json_file(self):
try:
with open(self.file_path, 'r', encoding='utf-8') as f:
return json.load(f)
except FileNotFoundError:
self.logger.exception(f"文件 {self.file_path} 不存在!")
except json.JSONDecodeError:
self.logger.exception(f"文件 {self.file_path} 内容不是有效的 JSON!")
def write_json_file(self, data: dict):
try:
with open(self.file_path, 'w', encoding='utf-8') as f:
json.dump(data, f, indent=4, ensure_ascii=False)
except FileNotFoundError:
self.logger.exception(f"文件 {self.file_path} 不存在!")
def update_json_file(self, value: str, parent_key: str, child_key: str = None):
try:
with open(self.file_path, 'r', encoding='utf-8') as f:
json_data = json.load(f)
if child_key is None:
# 无嵌套
json_data[parent_key] = value
else:
# 2级嵌套
json_data[parent_key][child_key] = value
# 将更新后的新数据写入json文件
self.write_json_file(json_data)
except FileNotFoundError:
self.logger.exception(f"文件 {self.file_path} 不存在!")
InI文件操作
class IniConfig:
def __init__(self, ini_file: str, folder="config"):
"""ini配置文件
Args:
ini_file: ini配置文件
folder: 配置文件路径
"""
self.logger = logger
self.config = ConfigParser()
self.file_path = Path(get_project_dir(), folder, ini_file)
print(self.file_path)
def load_file(self) -> None:
"""加载文件
Returns:
None
"""
try:
self.config.read(self.file_path, encoding="utf-8")
self.logger.debug(f"读取配置文件:【{self.file_path}】成功~")
except (FileNotFoundError, NoSectionError):
self.logger.exception(f"读取配置文件:【{self.file_path}】异常!")
def get_value(self, parent_key: str, child_key: str) -> str:
"""获取对应的值
Args:
parent_key: 父键
child_key: 子键
Returns:
data: 配置文件值
"""
self.load_file()
data = self.config.get(parent_key, child_key)
self.logger.debug(f"ini文件【{self.file_path}】加载成功!内容:{data}")
return data
CSV文件操作
class CsvConfig:
def __init__(self, csv_file: str, folder: str = "config"):
"""CsvConfig
Args:
csv_file: csv配置文件
folder: csv配置文件的路径
"""
self.logger = logger
self.file_path = Path(get_project_dir(), folder, csv_file)
print(self.file_path)
def read_csv_file(self):
try:
with open(self.file_path, 'r', encoding='utf-8') as f:
reader = csv.reader(f)
rows = []
for row in reader:
rows.append(row)
return rows
except FileNotFoundError:
self.logger.exception(f"文件 {self.file_path} 不存在!")
except csv.Error:
self.logger.exception(f"文件 {self.file_path} 内容不是有效的CSV!")
def write_csv_file(self, write_data: list):
try:
with open(self.file_path, 'a', newline='', encoding='utf-8') as f:
writer = csv.writer(f)
writer.writerows(write_data)
except csv.Error:
self.logger.exception(f"{write_data}数据写入csv文件失败!!")
最后运行结果