您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# Python文件流读写如何操作
## 1. 文件操作基础概念
### 1.1 什么是文件流
文件流(File Stream)是程序与文件之间数据传输的通道,Python通过内置的`open()`函数创建文件对象来实现文件流的读写操作。文件流可以分为:
- 输入流(读取数据)
- 输出流(写入数据)
### 1.2 文件打开模式
Python支持多种文件打开模式,通过`open()`函数的第二个参数指定:
| 模式 | 描述 |
|------|------|
| `'r'` | 只读(默认) |
| `'w'` | 写入(会覆盖原有内容) |
| `'a'` | 追加 |
| `'x'` | 独占创建(文件已存在则失败) |
| `'b'` | 二进制模式 |
| `'t'` | 文本模式(默认) |
| `'+'` | 读写模式 |
## 2. 基本读写操作
### 2.1 打开和关闭文件
```python
# 基本文件操作流程
file = open('example.txt', 'r') # 打开文件
content = file.read() # 读取内容
file.close() # 关闭文件
推荐使用with
语句自动管理文件关闭:
with open('example.txt', 'r') as file:
content = file.read()
# 文件会在代码块结束后自动关闭
Python提供多种读取方法:
# 读取整个文件
content = file.read()
# 按行读取全部内容
lines = file.readlines()
# 逐行读取(内存友好)
for line in file:
print(line.strip())
# 写入字符串
with open('output.txt', 'w') as file:
file.write("Hello, World!\n")
file.write("Second line\n")
# 写入多行
lines = ["First line\n", "Second line\n"]
with open('output.txt', 'w') as file:
file.writelines(lines)
处理图片、视频等非文本文件时需使用二进制模式:
# 复制图片文件
with open('input.jpg', 'rb') as src:
with open('output.jpg', 'wb') as dst:
dst.write(src.read())
with open('example.txt', 'r+') as file:
# 获取当前位置
pos = file.tell()
# 移动到文件开头
file.seek(0)
# 读取前5个字节
print(file.read(5))
# 移动到文件末尾
file.seek(0, 2)
# 禁用缓冲(立即写入)
with open('log.txt', 'w', buffering=0) as file:
file.write("Immediate write\n")
# 行缓冲(遇到换行符写入)
with open('log.txt', 'w', buffering=1) as file:
file.write("Line buffered\n")
# 手动刷新缓冲区
file.flush()
处理不同编码的文本文件:
# 指定编码(推荐始终明确指定)
with open('utf8_file.txt', 'r', encoding='utf-8') as file:
content = file.read()
# 处理编码错误
try:
with open('unknown.txt', 'r', encoding='utf-8') as file:
content = file.read()
except UnicodeDecodeError:
print("Encoding error occurred")
处理大文件时的内存优化方案:
# 逐块读取
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.dat'):
process(chunk)
from pathlib import Path
# 现代路径处理方式
file_path = Path('data') / 'subdir' / 'file.txt'
# 读取文件
content = file_path.read_text(encoding='utf-8')
# 写入文件
file_path.write_text("New content", encoding='utf-8')
import datetime
def write_log(message):
timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open('app.log', 'a') as log_file:
log_file.write(f"[{timestamp}] {message}\n")
import csv
# 读取CSV
with open('data.csv', 'r') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print(row)
# 写入CSV
data = [['Name', 'Age'], ['Alice', 25], ['Bob', 30]]
with open('output.csv', 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerows(data)
import configparser
config = configparser.ConfigParser()
config.read('config.ini')
# 获取配置
db_host = config['DATABASE']['Host']
# 修改配置
config['DATABASE']['Port'] = '5432'
with open('config.ini', 'w') as configfile:
config.write(configfile)
with
语句:确保文件正确关闭mmap
模块asyncio
和aiofiles
Python的文件流操作提供了灵活强大的文件处理能力,关键要点包括:
- 始终使用with
语句管理文件对象
- 明确指定文件编码
- 根据需求选择合适的读写方法
- 处理大文件时注意内存使用
- 使用pathlib
简化路径操作
掌握这些技术后,你可以高效地处理各种文件操作任务,从简单的文本处理到复杂的数据流水线。 “`
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。