惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

SecWiki News
SecWiki News
罗磊的独立博客
U
Unit 42
I
InfoQ
B
Blog RSS Feed
Google DeepMind News
Google DeepMind News
J
Java Code Geeks
Blog — PlanetScale
Blog — PlanetScale
The GitHub Blog
The GitHub Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
B
Blog
S
SegmentFault 最新的问题
V
Visual Studio Blog
Engineering at Meta
Engineering at Meta
Microsoft Security Blog
Microsoft Security Blog
月光博客
月光博客
Vercel News
Vercel News
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
博客园_首页
腾讯CDC
F
Fortinet All Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Hugging Face - Blog
Hugging Face - Blog
MongoDB | Blog
MongoDB | Blog
阮一峰的网络日志
阮一峰的网络日志
D
Docker
N
Netflix TechBlog - Medium
云风的 BLOG
云风的 BLOG
Apple Machine Learning Research
Apple Machine Learning Research
Microsoft Azure Blog
Microsoft Azure Blog
Martin Fowler
Martin Fowler
人人都是产品经理
人人都是产品经理
酷 壳 – CoolShell
酷 壳 – CoolShell
爱范儿
爱范儿
大猫的无限游戏
大猫的无限游戏
V
V2EX
Last Week in AI
Last Week in AI
博客园 - 司徒正美
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
IT之家
IT之家
L
LangChain Blog
WordPress大学
WordPress大学
Y
Y Combinator Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
M
MIT News - Artificial intelligence
The Cloudflare Blog
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享

博客园 - 箫笛

Tkinter - Entry 输入框组件 Tkinter - Button 组件 Tkinter - Label 组件 Tkinter - tk 变量 Tkinter - 事件与绑定 Tkinter - 几何管理器 Tkinter - 核心概念 Tkinter - 快速开始 Tkinter - 介绍 Python 编程 - 条件表达式 Python 编程 - 星号下划线参数释义 shell 编程 - shell 脚本的交互方式 Python insall - macOS 系统安装python的几种方式 Miniconda - Python 环境管理工具 Tkinter - Python GUI 开发 Python 编程 - 下划线命名的区别 Python 编程 - 元类编程 Python 编程 - 多重继承与MRO Python 编程 - 描述符协议 Python 编程 - 类型注解 Python 编程 - 生成器表达式 Python 编程 - 集合 Python 编程 - 装饰器 Python 编程 - 闭包 Python 编程 - 列表推导式 Python 编程 - 函数式编程 Python 编程 - lambda 函数 Python 编程 - 输入与输出 Python 编程 - 面向对象编程 Python 编程 - 元组(tuple) Python 编程 - 字符串(str) Python 编程 - 字典(dict) Python 编程 - 列表(list) Python 编程 - 数据类型和数据结构 Python 编程 - 语句 Python 编程 - 函数 windows - WSL 的安装与使用 shell编程 - dialog 程序使用指南 FE Team - 如何做好前端代码审查 git 提交的撤销和恢复 React15 - redux-saga 如何在saga中实现轮询接口调用? React15 - React CSS Modules BEM命名实践 React15 - React 15 中 componentWillReceiveProps 为什么会多次调用, 同时componentDidUpdate 也会多次调用? React15 - React15类组件多次执行render方法的原因? React15 - React15应用中代码逻辑复用方案 React15 - React状态同步问题解决 React15 - React 15 中 React.pureComponent 的使用场景 React15 - React 15应用在页面渲染时会多次执行类组件的render 函数的原因 React15 - React 15 中能用 componetDidUpdate 代替 componentWillReceiveProps 吗? React15 - React 15 生命周期函数详解 React15 - 如何在React 15中实现自定义的事件订阅与发送(例如组件间通信) React15 - React15应用中的事件订阅和发送机制 React15 - CSS中的BEM规范 React15 - React CSS Modules BEM命名实践 React15 - 写sass 样式文件,嵌套的结构好,还是扁平的结构好? React15 - sass 中 @mixin 和 @extend 的区别是什么? React15 - React 15 应用 如何使用Css moudules 方式进行模块化开发 React15 - React15应用Sass使用指南 React15 - React 15 应用如何进行性能优化?
Python 编程 - 文件操作
箫笛 · 2026-06-21 · via 博客园 - 箫笛

在 Python 3 中,文件操作主要通过内置的 open() 函数以及文件对象的方法来完成。下面从基础到进阶,全面介绍常用操作与最佳实践。


1. 打开文件:open()

f = open(file, mode='r', encoding=None, errors=None, newline=None, ...)

必需参数

  • file:文件路径(字符串或 pathlib.Path 对象)。

常用模式(mode)

模式 说明
'r' 只读(默认),文件必须存在
'w' 只写,覆盖原有内容,不存在则创建
'a' 追加,写入内容追加到末尾,不存在则创建
'x' 独占创建,文件存在则报错 FileExistsError
'b' 二进制模式(如 'rb''wb'
't' 文本模式(默认,如 'rt'
'+' 更新模式(读写,如 'r+''w+''a+'

常用参数

  • encoding:指定编码,Python 3 默认使用系统编码(如 UTF-8),但建议显式指定 encoding='utf-8'
  • errors:编码/解码错误处理方式,如 'strict'(默认)、'ignore''replace'
  • newline:控制换行符转换,取值 None'''\n''\r\n' 等。

2. 读取文件

2.1 读取全部内容

with open('data.txt', 'r', encoding='utf-8') as f:
    content = f.read()          # 返回字符串
    print(content)

2.2 按行读取

with open('data.txt', 'r', encoding='utf-8') as f:
    line = f.readline()          # 读一行
    lines = f.readlines()        # 读所有行,返回列表(每行带换行符)

2.3 迭代文件对象(最推荐,内存友好)

with open('data.txt', 'r', encoding='utf-8') as f:
    for line in f:               # 逐行迭代,不会一次加载全部
        print(line.strip())

2.4 读取指定字节数(二进制模式)

with open('data.bin', 'rb') as f:
    chunk = f.read(1024)         # 读取前1024字节

3. 写入文件

3.1 写入字符串(文本模式)

with open('out.txt', 'w', encoding='utf-8') as f:
    f.write('Hello, 世界!\n')
    f.write('第二行')

3.2 写入多行(可迭代对象)

lines = ['第一行\n', '第二行\n', '第三行']
with open('out.txt', 'w', encoding='utf-8') as f:
    f.writelines(lines)          # 不会自动添加换行,需自行包含

3.3 追加内容

with open('out.txt', 'a', encoding='utf-8') as f:
    f.write('追加内容')

4. 文件指针操作

  • tell():返回当前指针位置(字节数,文本模式下可能不是精确字符数)。
  • seek(offset, whence=0):移动指针。
    • whence=0:从文件开头偏移(默认)
    • whence=1:从当前位置偏移
    • whence=2:从文件末尾偏移
with open('data.txt', 'rb') as f:
    print(f.tell())      # 0
    f.seek(10)           # 跳到第10个字节
    data = f.read(5)

5. 自动管理资源:with 语句

使用 with 可以确保文件在代码块结束后自动关闭,即使发生异常也会正确释放资源,是推荐的标准写法

with open('file.txt', 'r') as f:
    data = f.read()
# 此处文件已自动关闭

6. 异常处理

手动控制时,需要 try...finally 保证关闭:

f = open('file.txt', 'r')
try:
    data = f.read()
finally:
    f.close()

或者使用 with 更简洁。


7. 二进制文件操作

处理图片、音频、压缩包等非文本文件,使用 'rb' / 'wb' 模式,不要指定 encoding

# 复制图片
with open('src.jpg', 'rb') as src, open('dst.jpg', 'wb') as dst:
    dst.write(src.read())

8. 文件对象常用属性

  • f.name:文件名
  • f.mode:打开模式
  • f.closed:是否已关闭
  • f.encoding:编码(文本模式)

9. 使用 pathlib 进行路径操作(Python 3.4+)

pathlib 提供面向对象的路径管理,可与 open() 结合:

from pathlib import Path

p = Path('data.txt')
with p.open('r', encoding='utf-8') as f:
    content = f.read()

10. 常见问题与最佳实践

  1. 始终指定 encoding,避免跨平台乱码。
  2. 优先使用 with,保证自动关闭。
  3. 处理大文件时,逐行或分块读取,避免 read() 一次性加载。
  4. 写入时注意换行符:Python 会按系统风格转换换行(\n -> \r\n 在 Windows),如需完全控制可用 newline=''
  5. 文件不存在时,'r' 模式抛出 FileNotFoundError'w' / 'a' 会自动创建。
  6. 权限问题:确保程序有相应读写权限。

11. 完整示例:读取 CSV 并处理

import csv

with open('data.csv', 'r', encoding='utf-8') as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

总结

操作 方法
打开 open()
读取全部 read()
读取一行 readline()
读取所有行 readlines() 或迭代
写入 write() / writelines()
关闭 close()with
指针 seek() / tell()

掌握以上内容,足以应对绝大多数 Python 文件操作场景。如有特殊需求(如内存映射、临时文件等),可进一步查阅标准库 iotempfile 等模块。