当前位置: 首页 > news >正文

Python文件操作完全指南:从入门到精通

计算机的文件系统是一种存储和组织计算机数据的方法,它使得对数据的访问和查找变得容易,文件系统使用文件树形目录的抽象逻辑概念代替了硬盘、光盘、闪存等物理设备的数据块概念,用户使用文件系统来保存数据时,不必关心数据实际保存在硬盘的哪个数据块上,只需要记住这个文件的路径和文件名。

实际开发中常常会遇到对数据进行持久化的场景,所谓持久化是指将数据从无法长久保存数据的存储介质(通常是内存)转移到可以长久保存数据的存储介质(通常是硬盘)中。实现数据持久化最直接简单的方式就是通过文件系统将数据保存到文件中。

文件打开和关闭文件

有了文件系统,我们可以非常方便的通过文件来读写数据;在Python中要实现文件操作是非常简单的。我们可以使用Python内置的open函数来打开文件,在使用open函数时,我们可以通过函数的参数指定文件名操作模式字符编码等信息,接下来就可以对文件进行读写操作了。这里所说的操作模式是指要打开什么样的文件(字符文件或二进制文件)以及做什么样的操作(读、写或追加),具体如下表所示

操作模式

具体含义

'r'

读取 (默认)

'w'

写入(会先截断之前的内容)

'x'

写入,如果文件已经存在会产生异常

'a'

追加,将内容写入到已有文件的末尾

'b'

二进制模式

't'

文本模式(默认)

'+'

更新(既可以读又可以写)

Python的open()函数是文件操作的核心函数,用于打开文件并返回一个文件对象。让我详细解释它的用法:

基本语法:

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

主要参数:

  1. file(必需参数)

文件路径,可以是绝对路径或相对路径
可以是字符串或路径对象

  1. mode(模式参数)

文本模式:

'r':只读模式(默认)
'w':写入模式,会覆盖原文件
'a':追加模式,在文件末尾添加内容
'x':创建模式,文件存在时会报错
'r+':读写模式

二进制模式:

'rb':二进制只读
'wb':二进制写入
'ab':二进制追加
'r+b':二进制读写

  1. encoding(编码参数)

指定文本文件的编码格式
常用:'utf-8'、'gbk'、'ascii'等
只在文本模式下有效

  1. buffering(缓冲参数)

-1:系统默认缓冲(默认值)
0:无缓冲(仅二进制模式)
1:行缓冲(仅文本模式)

>1:指定缓冲区大小

手动关闭

# 需要手动关闭
f = open('file.txt', 'r')
content = f.read()
f.close()  # 必须记得关闭

with open()语法

with open() 是Python中安全打开和处理文件的标准方式,它结合了两个重要概念:

1. with 语句(上下文管理器)
  • 一种资源管理的语法结构
  • 确保资源被正确获取和释放
  • 自动处理清理工作(如关闭文件)
2. open() 函数
  • Python的内置函数,用于打开文件
  • 返回一个文件对象

使用示例 :

基本读取 :

# 读取整个文件
with open('example.txt', 'r', encoding='utf-8') as f:content = f.read()print(content)# 逐行读取
with open('example.txt', 'r', encoding='utf-8') as f:for line in f:print(line.strip())

写入文件 :

# 覆盖写入
with open('output.txt', 'w', encoding='utf-8') as f:f.write('Hello, World!')# 追加写入
with open('output.txt', 'a', encoding='utf-8') as f:f.write('\nNew line')

二进制操作 :

# 读取二进制文件
with open('image.jpg', 'rb') as f:data = f.read()# 写入二进制文件
with open('copy.jpg', 'wb') as f:f.write(data)

文件基本操作

1、首先创建一个包含诗歌的example.txt文件

# 首先创建一个包含诗歌的example.txt文件
def create_poem_file():"""创建包含诗歌的example.txt文件"""poem = """静夜思
李白床前明月光,
疑是地上霜。
举头望明月,
低头思故乡。春晓
孟浩然春眠不觉晓,
处处闻啼鸟。
夜来风雨声,
花落知多少。登鹳雀楼
王之涣白日依山尽,
黄河入海流。
欲穷千里目,
更上一层楼。"""# 使用with语句创建文件(推荐方式)with open('example.txt', 'w', encoding='utf-8') as f:f.write(poem)print("✅ example.txt 文件创建成功!")

2、读取整个文件内容

def read_entire_file():"""读取整个文件内容"""print("\n📖 读取整个文件内容:")print("-" * 40)try:with open('example.txt', 'r', encoding='utf-8') as f:content = f.read()print(content)except FileNotFoundError:print("❌ 文件不存在,请先运行 create_poem_file()")except Exception as e:print(f"❌ 读取文件时发生错误:{e}")

3、逐行读取文件

def read_line_by_line():"""逐行读取文件"""print("\n📝 逐行读取文件:")print("-" * 40)try:with open('example.txt', 'r', encoding='utf-8') as f:line_number = 1for line in f:print(f"第{line_number:2d}行: {line.rstrip()}")line_number += 1except FileNotFoundError:print("❌ 文件不存在")except Exception as e:print(f"❌ 读取文件时发生错误:{e}")

4、读取所有行到列表

def read_all_lines():"""读取所有行到列表"""print("\n📋 读取所有行到列表:")print("-" * 40)try:with open('example.txt', 'r', encoding='utf-8') as f:lines = f.readlines()print(f"文件共有 {len(lines)} 行")print("非空行内容:")for i, line in enumerate(lines, 1):if line.strip():  # 跳过空行print(f"  {i}: {line.rstrip()}")except FileNotFoundError:print("❌ 文件不存在")except Exception as e:print(f"❌ 读取文件时发生错误:{e}")

5、统计文件信息

def analyze_poem_file():"""分析诗歌文件的统计信息"""print("\n📊 文件统计信息:")print("-" * 40)try:with open('example.txt', 'r', encoding='utf-8') as f:content = f.read()lines = content.split('\n')total_lines = len(lines)non_empty_lines = len([line for line in lines if line.strip()])total_chars = len(content)total_chars_no_space = len(content.replace(' ', '').replace('\n', ''))print(f"总行数: {total_lines}")print(f"非空行数: {non_empty_lines}")print(f"总字符数: {total_chars}")print(f"总字符数(不含空格换行): {total_chars_no_space}")# 统计每首诗poems = content.split('\n\n')print(f"诗歌数量: {len([p for p in poems if p.strip()])}")except FileNotFoundError:print("❌ 文件不存在")except Exception as e:print(f"❌ 分析文件时发生错误:{e}")

6、在文件末尾追加内容

def append_to_file():"""在文件末尾追加新的诗歌"""new_poem = """相思
王维红豆生南国,
春来发几枝。
愿君多采撷,
此物最相思。"""print("\n➕ 在文件末尾追加新诗:")print("-" * 40)try:with open('example.txt', 'a', encoding='utf-8') as f:f.write(new_poem)print("✅ 成功追加新诗歌到文件末尾")except Exception as e:print(f"❌ 追加内容时发生错误:{e}")

7、搜索特定内容

def search_in_file(keyword):"""在文件中搜索包含关键词的行"""print(f"\n🔍 搜索包含'{keyword}'的行:")print("-" * 40)try:with open('example.txt', 'r', encoding='utf-8') as f:line_number = 1found_lines = []for line in f:if keyword in line:found_lines.append((line_number, line.strip()))line_number += 1if found_lines:print(f"找到 {len(found_lines)} 行包含'{keyword}':")for line_num, content in found_lines:print(f"  第{line_num}行: {content}")else:print(f"未找到包含'{keyword}'的行")except FileNotFoundError:print("❌ 文件不存在")except Exception as e:print(f"❌ 搜索时发生错误:{e}")

8、 备份文件

def backup_file():"""创建文件备份"""print("\n💾 创建文件备份:")print("-" * 40)try:# 读取原文件with open('example.txt', 'r', encoding='utf-8') as source:content = source.read()# 写入备份文件backup_name = 'example_backup.txt'with open(backup_name, 'w', encoding='utf-8') as backup:backup.write(content)print(f"✅ 文件已备份为: {backup_name}")except FileNotFoundError:print("❌ 原文件不存在")except Exception as e:print(f"❌ 备份文件时发生错误:{e}")

9、主函数演示所有功能

def main():"""主函数:演示所有文件操作功能"""print("🎭 Python诗歌文件操作演示")print("=" * 50)# 创建诗歌文件create_poem_file()# 演示各种读取方式read_entire_file()read_line_by_line()read_all_lines()# 分析文件analyze_poem_file()# 搜索功能search_in_file("月")search_in_file("春")# 追加内容append_to_file()# 重新分析文件(显示追加后的变化)print("\n📈 追加内容后的文件统计:")analyze_poem_file()# 备份文件backup_file()print("\n🎉 演示完成!")# 运行演示
if __name__ == "__main__":main()

异常处理机制

使用Python的异常机制对可能在运行时发生状况的代码进行适当的处理。Python中和异常相关的关键字有五个,分别是tryexceptelsefinallyraise

1. 异常处理基础语法

print("\n1. 异常处理基础语法")
print("-" * 40)# 基本的try-except结构
def basic_exception_handling():"""基本异常处理示例"""print("基本异常处理:")try:result = 10 / 0  # 这会引发ZeroDivisionErrorexcept ZeroDivisionError:print("❌ 捕获到除零错误!")result = Nonereturn resultbasic_exception_handling()

2. 捕获多种异常

# 捕获多种异常
def multiple_exceptions():"""处理多种异常类型"""print("\n处理多种异常:")test_cases = [lambda: 10 / 0,           # ZeroDivisionErrorlambda: int("abc"),       # ValueErrorlambda: [1, 2][5],        # IndexError]for i, test_func in enumerate(test_cases):try:result = test_func()print(f"测试{i+1}成功: {result}")except ZeroDivisionError:print(f"测试{i+1}: ❌ 除零错误")except ValueError:print(f"测试{i+1}: ❌ 值错误")except IndexError:print(f"测试{i+1}: ❌ 索引错误")

3. 使用else和finally

# 使用else和finally
def complete_exception_structure():"""完整的异常处理结构"""print("\n完整异常处理结构:")def test_operation(value):try:result = 100 / valueprint(f"✅ 计算成功: 100 / {value} = {result}")except ZeroDivisionError:print("❌ 不能除以零")result = Noneelse:print("📝 没有异常发生,执行else块")finally:print("🔚 无论如何都会执行finally块")return resulttest_operation(5)   # 正常情况print()test_operation(0)   # 异常情况complete_exception_structure()

异常结构层次

  1. BaseException - 所有异常的根基类
  2. 四大直接子类
    • SystemExit(系统退出)
    • KeyboardInterrupt(键盘中断)
    • GeneratorExit(生成器退出)
    • Exception(程序异常基类)
  1. Exception的主要分支
    • 算术错误系列
    • 查找错误系列
    • 操作系统错误系列
    • 语法错误系列
    • 值错误系列
    • 警告系列

http://www.lqws.cn/news/536923.html

相关文章:

  • 基于SpringBoot的智慧旅游系统
  • 从零到一训练一个 0.6B 的 MoE 大语言模型
  • Java——Spring 非注解开发:IoC/DI 与 Bean 管理实战(含第三方组件整合)
  • python的银行柜台管理系统
  • easyExcel导入多sheet的Excel,存在合并单元格、列不固定的情况
  • # RK3588 Linux SDK 完整问题解决记录-编译内核头文件
  • 【Pandas】pandas DataFrame first_valid_index
  • 跨越十年的C++演进:C++14新特性全解析
  • 手机控车远程启动一键启动
  • C++智能指针概念及std::unique_ptr使用介绍
  • 使用docker搭建redis主从架构,一主2从
  • day48-硬件学习之GPT定时器、UART及I2C
  • 日语学习-日语知识点小记-进阶-JLPT-真题训练-N2阶段(4):2022年12月2023年12月
  • 机器学习18-强化学习RLHF
  • python基于协同过滤的动漫推荐系统
  • 华为云Flexus+DeepSeek征文|一键部署知识库搜索增强版搭建AI Agent
  • 《仿盒马》app开发技术分享-- 逻辑优化第三弹(83)
  • 新手向:Neo4j的安装与使用
  • 供应链数据可视化大屏
  • OneCode框架 Tree 相关注解使用说明
  • 服务器的安装与安全设置 域环境的搭建和管理 Windows基本配置 网络服务常用网络命令的应用 安全管理Windows Server 2019
  • 独立开发还能做吗
  • Git-git worktree的使用
  • 测试方法的分类
  • recipes的版本比较老如何更新到新版本?
  • 板凳-------Mysql cookbook学习 (十--11)
  • AAAI 2025论文分享│面向生物医学的具有像素级洞察力的多模态大语言模型
  • day43 打卡
  • Redis主从架构哨兵模式
  • Rk3568驱动开发_Key驱动_13