元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
Python基础语法
Python环境安装与配置
第一个Python程序
变量与数据类型
字面量详解
基本运算符
流程控制语句
包管理与虚拟环境
▶
Python数据结构
列表(List)详解
元组(Tuple)使用指南
字典(Dict)完全解析
集合(Set)操作大全
▶
函数与模块
函数定义与参数传递
Lambda表达式
模块导入与使用
常用内置函数
▶
面向对象编程
类与对象
继承与多态
魔术方法解析
装饰器原理与应用
▶
Python类型系统
类型注解(Type Hints)
Pydantic基础
Pydantic高级特性
typing模块基础
泛型类型详解
泛型类详解
Callable类型详解
Awaitable类型详解
类型变量与约束
类型别名与Protocol
TypedDict详解
Annotated类型
Reducer类型
类型检查工具使用
类型注解最佳实践
▶
关键字
pass关键字
raise关键字
global关键字
nonlocal关键字
yield关键字
assert关键字
with关键字
async/await关键字
▶
包管理
pip包管理基础
虚拟环境管理
包管理工具对比
requirements.txt规范
依赖管理与requirements.txt
setup.py配置说明
Poetry项目管理工具
Conda包管理系统
打包与发布Python包
PyPI发布流程
私有PyPI仓库
▶
Python高级特性
迭代器与生成器
多线程编程
协程与异步IO
元编程入门
反射机制详解
描述符协议
上下文管理器协议
垃圾回收机制
内存管理深度解析
性能优化指南
▶
文件与异常处理
文件读写操作
JSON数据解析
异常处理机制
上下文管理器
发布时间:
2025-03-24 13:21
↑
☰
# Python文件读写操作详解 本文将详细介绍Python中的文件读写操作,帮助你掌握文件处理的基本技能。 ## 文件操作基础 ### 打开文件 在Python中,使用`open()`函数打开文件: ```python # 基本语法 file = open('filename', 'mode', encoding='encoding') # 常用打开模式 # 'r': 只读模式(默认) # 'w': 写入模式(会覆盖原有内容) # 'a': 追加模式 # 'x': 独占写入模式 # 'b': 二进制模式 # '+': 读写模式 # 示例 file = open('test.txt', 'r', encoding='utf-8') ``` ### 关闭文件 ```python # 手动关闭 file.close() # 使用with语句(推荐) with open('test.txt', 'r') as file: content = file.read() # 文件会自动关闭 ``` ## 文件读取操作 ### 读取整个文件 ```python # 读取所有内容 with open('test.txt', 'r') as file: content = file.read() print(content) # 读取指定字节数 with open('test.txt', 'r') as file: content = file.read(10) # 读取前10个字符 print(content) ``` ### 逐行读取 ```python # 读取单行 with open('test.txt', 'r') as file: line = file.readline() print(line) # 读取所有行到列表 with open('test.txt', 'r') as file: lines = file.readlines() for line in lines: print(line.strip()) # strip()去除换行符 # 直接遍历文件对象 with open('test.txt', 'r') as file: for line in file: print(line.strip()) ``` ## 文件写入操作 ### 写入文本 ```python # 写入字符串 with open('test.txt', 'w') as file: file.write('Hello, World!\n') file.write('Python文件操作\n') # 写入多行 lines = ['第一行\n', '第二行\n', '第三行\n'] with open('test.txt', 'w') as file: file.writelines(lines) ``` ### 追加内容 ```python # 追加模式 with open('test.txt', 'a') as file: file.write('追加的内容\n') ``` ## 文件指针操作 ### 移动文件指针 ```python # seek()方法 with open('test.txt', 'r') as file: # 移动到文件开头 file.seek(0) # 移动到指定位置 file.seek(10) # 获取当前位置 position = file.tell() print(f'当前位置: {position}') ``` ## 二进制文件操作 ### 读取二进制文件 ```python # 读取图片文件 with open('image.jpg', 'rb') as file: data = file.read() print(f'文件大小: {len(data)} 字节') # 分块读取大文件 def read_in_chunks(file_path, chunk_size=1024): with open(file_path, 'rb') as file: while True: chunk = file.read(chunk_size) if not chunk: break yield chunk # 使用示例 for chunk in read_in_chunks('large_file.bin'): process_chunk(chunk) # 处理数据块 ``` ### 写入二进制文件 ```python # 写入二进制数据 data = bytes([65, 66, 67, 68]) # ASCII: ABCD with open('binary.bin', 'wb') as file: file.write(data) # 复制文件 def copy_file(src_path, dst_path, chunk_size=1024): with open(src_path, 'rb') as src, open(dst_path, 'wb') as dst: while True: chunk = src.read(chunk_size) if not chunk: break dst.write(chunk) ``` ## 实际应用示例 ### 1. 日志记录器 ```python from datetime import datetime class Logger: def __init__(self, filename): self.filename = filename def log(self, message, level='INFO'): timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') log_message = f'[{timestamp}] {level}: {message}\n' with open(self.filename, 'a') as file: file.write(log_message) def clear_log(self): with open(self.filename, 'w') as file: file.write('') # 清空文件 # 使用示例 logger = Logger('app.log') logger.log('应用程序启动') logger.log('发生错误', 'ERROR') ``` ### 2. 配置文件处理 ```python class ConfigParser: def __init__(self, filename): self.filename = filename self.config = {} def load(self): try: with open(self.filename, 'r') as file: for line in file: line = line.strip() if line and not line.startswith('#'): key, value = line.split('=', 1) self.config[key.strip()] = value.strip() except FileNotFoundError: print(f'配置文件 {self.filename} 不存在') def get(self, key, default=None): return self.config.get(key, default) def set(self, key, value): self.config[key] = value def save(self): with open(self.filename, 'w') as file: for key, value in self.config.items(): file.write(f'{key}={value}\n') # 使用示例 config = ConfigParser('config.ini') config.load() print(config.get('database_host', 'localhost')) config.set('database_port', '5432') config.save() ``` ### 3. CSV文件处理 ```python class CSVHandler: def __init__(self, filename): self.filename = filename def read_csv(self): data = [] with open(self.filename, 'r') as file: # 跳过标题行 headers = file.readline().strip().split(',') # 读取数据行 for line in file: values = line.strip().split(',') row = dict(zip(headers, values)) data.append(row) return data def write_csv(self, data, headers=None): with open(self.filename, 'w') as file: # 写入标题行 if headers: file.write(','.join(headers) + '\n') # 写入数据行 for row in data: if isinstance(row, dict): # 字典格式数据 values = [str(row.get(h, '')) for h in headers] else: # 列表格式数据 values = [str(v) for v in row] file.write(','.join(values) + '\n') # 使用示例 csv_handler = CSVHandler('data.csv') # 写入数据 headers = ['name', 'age', 'city'] data = [ {'name': 'Alice', 'age': '25', 'city': 'Beijing'}, {'name': 'Bob', 'age': '30', 'city': 'Shanghai'} ] csv_handler.write_csv(data, headers) # 读取数据 read_data = csv_handler.read_csv() for row in read_data: print(row) ``` ## 最佳实践 1. **始终使用with语句** ```python # 不好的做法 file = open('file.txt', 'r') try: content = file.read() finally: file.close() # 好的做法 with open('file.txt', 'r') as file: content = file.read() ``` 2. **指定正确的编码** ```python # 不好的做法 with open('file.txt', 'r') as file: content = file.read() # 好的做法 with open('file.txt', 'r', encoding='utf-8') as file: content = file.read() ``` 3. **大文件处理** ```python # 不好的做法 with open('large_file.txt', 'r') as file: content = file.read() # 读取整个文件到内存 # 好的做法 with open('large_file.txt', 'r') as file: for line in file: # 逐行处理 process_line(line) ``` 4. **异常处理** ```python # 不好的做法 with open('file.txt', 'r') as file: content = file.read() # 好的做法 try: with open('file.txt', 'r') as file: content = file.read() except FileNotFoundError: print('文件不存在') except PermissionError: print('没有读取权限') except Exception as e: print(f'发生错误: {e}') ``` 通过本文的学习,你应该已经掌握了Python文件操作的基本知识和实际应用方法。文件操作是编程中的重要基础,合理使用这些操作可以帮助你更好地处理数据和构建应用程序。继续练习和探索,你会发现更多文件操作的应用场景!