新闻详情

新闻详情

首页 / 资讯中心 / 详情

一篇读懂python文件读写

发布时间:2026/9/12 9:20:40来源:尧图网络
一篇读懂python文件读写
首先获取到需要读取文件的根目录def get_project_dir(): 获取当前项目的根路径 :return: 返回根路径的绝对路径 project_dir os.path.abspath(os.path.join(os.path.dirname(__file__), ../..)) return project_dirYaml文件操作class YamlConfig: def __init__(self, yaml_file, folderconfig): 初始化 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, encodingutf-8) as f: yaml.safe_dump(data, f, allow_unicodeTrue) self.logger.debug(fyaml文件【{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, encodingutf-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, encodingutf-8) as f: data yaml.safe_load(f.read()) self.logger.debug(fyaml文件【{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 NoneJson文件操作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, encodingutf-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, encodingutf-8) as f: json.dump(data, f, indent4, ensure_asciiFalse) 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, encodingutf-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, folderconfig): 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, encodingutf-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(fini文件【{self.file_path}】加载成功内容{data}) return dataCSV文件操作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, encodingutf-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, encodingutf-8) as f: writer csv.writer(f) writer.writerows(write_data) except csv.Error: self.logger.exception(f{write_data}数据写入csv文件失败)最后运行结果
网站建设高端定制企业官网
RELATED

相关资讯

更多精彩内容,欢迎继续阅读

较早相关资讯

最新相关资讯

C语言内存管理:原理、问题与优化实践 2026/9/12 9:50:44

C语言内存管理:原理、问题与优化实践

1. 为什么需要理解C语言内存管理在嵌入式开发中遇到过一个真实案例:某智能家居设备在运行72小时后必然死机。经过排查发现是开发者在处理传感器数据时,循环调用malloc()却忘记free(),导致内存泄漏最终耗尽系统资源。这个经历让我深刻意识到&a…

阅读更多 →
Repomix 隐私政策技术解读:CLI 本地处理、网站临时上传与浏览器扩展的最小权限设计 2026/9/12 9:50:44

Repomix 隐私政策技术解读:CLI 本地处理、网站临时上传与浏览器扩展的最小权限设计

Repomix 隐私政策技术解读:CLI 本地处理、网站临时上传与浏览器扩展的最小权限设计 【免费下载链接】repomix 📦 Repomix is a powerful tool that packs your entire repository into a single, AI-friendly file. Perfect for when you need to feed y…

阅读更多 →
学生装机指南:Intel Ultra 7 265K处理器与高性价比配置方案 2026/9/12 9:50:44

学生装机指南:Intel Ultra 7 265K处理器与高性价比配置方案

1. 为什么选择Intel Ultra 7 265K作为学生装机核心Intel Ultra 7 265K这颗处理器可以说是专为学生群体量身定制的全能型选手。我帮不少学弟学妹装过机,发现他们最常遇到的痛点就是:既要跑专业软件,又想打游戏,预算还特别紧张。265…

阅读更多 →
研发型与通用型项目管理系统的差异与选型指南 2026/9/12 9:50:43

研发型与通用型项目管理系统的差异与选型指南

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

阅读更多 →
Beancount双重记账系统:从原理到实战应用 2026/9/12 9:50:43

Beancount双重记账系统:从原理到实战应用

1. Beancount:双重记账系统的核心价值第一次接触Beancount时,我被它简洁的文本记账方式所震撼。与传统的GUI记账软件不同,这个基于Python的命令行工具通过纯文本文件记录每笔交易,却能自动生成完整的财务报表。它的设计哲学让我想…

阅读更多 →
5 步跑通个人知识库助手:LLM Universe 大模型应用开发完整教程 2026/9/12 9:47:43

5 步跑通个人知识库助手:LLM Universe 大模型应用开发完整教程

5 步跑通个人知识库助手:LLM Universe 大模型应用开发完整教程 【免费下载链接】llm-universe 本项目是一个面向小白开发者的大模型应用开发教程,在线阅读地址:https://datawhalechina.github.io/llm-universe/ 项目地址: https://gitcode.…

阅读更多 →

今日资讯

本周资讯

本月资讯

看完文章仍有疑问?

联系尧图顾问,获取一对一建站咨询

立即免费咨询 📞 400-888-8888
📞