网站首页 > 技术文章 正文
以下是一份详细的 Python 基础文件操作指南,包含常见操作和示例代码:
一、文件操作基本流程
- 打开文件 → 2. 操作文件 → 3. 关闭文件
二、打开文件
使用 open() 函数:
python
复制
file = open(filename, mode='r', encoding='utf-8')
参数说明:
- filename: 文件路径(绝对路径或相对路径)
- mode: 文件打开模式(见下方模式表)
- encoding: 编码格式(常用 utf-8)
文件模式表
模式 | 描述 |
r | 只读(默认模式) |
w | 写入(覆盖原有内容,文件不存在则创建) |
a | 追加(在文件末尾添加内容) |
x | 创建新文件并写入(文件已存在则报错) |
b | 二进制模式(例如 rb 或 wb) |
+ | 读写模式(例如 r+ 或 w+) |
三、读取文件内容
1. 读取全部内容
python
with open('test.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
2. 逐行读取
python
with open('test.txt', 'r') as f:
for line in f:
print(line.strip()) # 去除换行符
3. 读取指定字节数
python
with open('test.txt', 'r') as f:
chunk = f.read(100) # 读取前100个字符
4. 读取所有行到列表
python
with open('test.txt', 'r') as f:
lines = f.readlines() # 返回列表,每行作为一个元素
四、写入文件
1. 写入字符串
python
with open('output.txt', 'w', encoding='utf-8') as f:
f.write("Hello, World!\n")
f.write("第二行内容")
2. 写入多行(列表)
python
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open('output.txt', 'w') as f:
f.writelines(lines)
3. 追加内容
python
with open('output.txt', 'a') as f:
f.write("追加的内容\n")
五、文件指针操作
1. 获取当前指针位置
python
position = f.tell()
2. 移动文件指针
python
f.seek(offset, whence)
- offset: 偏移量(字节)
- whence: 参考位置(0: 文件头,1: 当前位置,2: 文件尾)
示例:
python
with open('test.txt', 'r') as f:
f.seek(10) # 移动到第10字节
print(f.read(5)) # 读取接下来5个字符
六、关闭文件
方法1:手动关闭
python
f = open('test.txt', 'r')
# ...操作文件...
f.close() # 必须显式关闭
方法2:自动关闭(推荐)
使用 with 语句会在代码块结束后自动关闭文件:
python
with open('test.txt', 'r') as f:
# ...操作文件...
# 此处文件已自动关闭
七、异常处理
python
try:
with open('test.txt', 'r') as f:
content = f.read()
except FileNotFoundError:
print("文件不存在!")
except IOError:
print("读写错误!")
finally:
print("操作结束")
八、二进制文件操作
适用于图片、视频等非文本文件:
python
# 读取二进制文件
with open('image.jpg', 'rb') as f:
data = f.read()
# 写入二进制文件
with open('copy.jpg', 'wb') as f:
f.write(data)
九、常用文件操作函数
1. 检查文件/目录是否存在
python
import os
exists = os.path.exists('test.txt')
2. 删除文件
python
import os
os.remove('test.txt')
3. 重命名文件
python
import os
os.rename('old.txt', 'new.txt')
4. 获取文件大小
python
import os
size = os.path.getsize('test.txt')
十、综合示例
复制文件内容:
python
with open('source.txt', 'r') as src, open('dest.txt', 'w') as dst:
for line in src:
dst.write(line)
注意事项
- 使用 with 语句可避免忘记关闭文件
- 写入模式 w 会覆盖原文件内容
- 操作二进制文件时务必使用 b 模式
- 文件路径需注意跨平台兼容性(Windows 使用 \,Linux/macOS 使用 /)
掌握这些操作即可应对大部分文件处理需求!
猜你喜欢
- 2025-05-02 python执行.sql语法和文件(python oracle sql语句跟参数)
- 2025-05-02 python unittest 基本用法(python中testcase)
- 2025-05-02 免费定时运行Python程序并存储输出文档的服务推荐
- 2025-05-02 20 天学 Python 文件操作:Day 1 从 open() 开始
- 2025-05-02 一文掌握Python找到文件操作(python找到文件夹下指定文件)
- 2025-05-02 python 文件操作(python 文件操作模块)
- 2025-05-02 pdb,让python文件在linux中跑起来
- 2025-05-02 IDEA中配置Python环境并运行(idea 运行python)
- 2025-05-02 14《Python 办公自动化教程》os 模块操作文件与文件夹
- 2025-05-02 Python自动化办公自学笔记(八)文件操作
- 261℃Python短文,Python中的嵌套条件语句(六)
- 261℃python笔记:for循环嵌套。end=""的作用,图形打印
- 260℃PythonNet:实现Python与.Net代码相互调用!
- 255℃Python实现字符串小写转大写并写入文件
- 254℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 110℃原来2025是完美的平方年,一起探索六种平方的算吧
- 94℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 87℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)