一、为什么需要文件?
在程序运行过程中:
-
变量只能保存临时数据
-
程序结束后,数据就会消失
如果想要长期保存数据,就必须使用------
💡 文件(File)
二、文件的分类
Python 中的文件主要分为两大类:
| 类型 | 特点 |
|---|---|
| 文本文件 | 可直接阅读,如 txt、csv、log |
| 二进制文件 | 需要专门软件解析,如图片、视频、exe |
三、文件操作的基本步骤
不管是读还是写,文件操作都遵循三个步骤:
-
打开文件
-
读写文件
-
关闭文件
四、打开文件------open() 函数
1. 基本语法
python
file_obj = open(file, mode='r', encoding=None)
参数说明:
| 参数 | 含义 |
|---|---|
| file | 文件路径 |
| mode | 打开模式 |
| encoding | 编码格式 |
2. 常见打开模式
| 模式 | 作用 |
|---|---|
| r | 只读(默认) |
| w | 写入(清空原内容) |
| a | 追加写 |
| x | 创建写(已存在则失败) |
| b | 二进制模式 |
| + | 可读可写 |
示例:
python
f = open('test.txt', 'r', encoding='utf-8')
3. 路径问题
- 绝对路径:
python
f = open('D:/data/test.txt')
- 相对路径:
python
f = open('./test.txt')
五、读取文件内容
Python 提供了多种读取方法:
1. read()
python
f.read(size)
-
不传参数:读取全部内容
-
传参数:读取指定字符数
示例:
python
with open('test.txt', 'r', encoding='utf-8') as f:
content = f.read()
2. readline()
每次读取一行:
python
line = f.readline()
3. readlines()
一次性读取为列表:
python
lines = f.readlines()
4. 文件遍历(最常用)
python
with open('test.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip())
👍 推荐方式:省内存、安全高效
六、关闭文件
传统方式:
python
f = open('test.txt')
...
f.close()
更推荐:with 语句
python
with open('test.txt') as f:
...
优点:
-
自动关闭
-
即使异常也安全
-
代码更优雅
七、写入文件
1. write()
python
with open('a.txt', 'w', encoding='utf-8') as f:
f.write("hello world")
-
w:清空后写
-
a:追加写
2. writelines()
写入字符串列表:
python
lines = ['a\n', 'b\n', 'c\n']
with open('a.txt', 'w') as f:
f.writelines(lines)
八、文件定位操作
1. tell()
获取当前位置:
python
pos = f.tell()
2. seek()
移动指针:
python
f.seek(0)
参数:
| 值 | 含义 |
|---|---|
| 0 | 文件开头 |
| 1 | 当前位置 |
| 2 | 文件结尾 |
九、文件拷贝与重命名
1. 文件拷贝
核心思路:
-
读原文件
-
写新文件
python
src = open('a.txt', 'r')
dst = open('b.txt', 'w')
dst.write(src.read())
src.close()
dst.close()
2. 文件重命名
python
import os
os.rename('old.txt', 'new.txt')
十、目录操作
需要使用:
python
import os
import shutil
1. 创建目录
python
os.mkdir('test')
2. 删除目录
python
shutil.rmtree('test')
3. 获取目录列表
python
os.listdir('path')
十一、路径操作
1. 判断是否绝对路径
python
os.path.isabs(path)
2. 转为绝对路径
python
os.path.abspath(path)
3. 获取当前路径
python
os.getcwd()
4. 判断路径是否存在
python
os.path.exists(path)
5. 拼接路径(重点)
python
os.path.join(p1, p2)
👍 跨平台最推荐的方式
十二、CSV 文件操作
CSV 本质:
-
逗号分隔的表格文本
-
行列结构
1. 读取 CSV
python
with open('score.csv') as f:
data = [line.strip().split(',') for line in f]
2. 写入 CSV
python
with open('out.csv', 'w') as f:
f.write(','.join(row) + '\n')
实例:成绩排序
步骤:
-
读 CSV
-
计算总分
-
排序
-
写入新文件
(此处可扩展为完整代码实例)
十三、JSON 文件操作
1. JSON 特点
-
轻量级
-
跨语言
-
键必须双引号
2. 核心函数
python
import json
| 函数 | 作用 |
|---|---|
| dumps | 对象 → JSON字符串 |
| loads | JSON字符串 → 对象 |
| dump | 写入文件 |
| load | 从文件读取 |
3. 示例
写 JSON:
python
with open('data.json','w',encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
读 JSON:
python
with open('data.json','r') as f:
data = json.load(f)
十四、pandas 文件操作(进阶)
第三方库:
bash
pip install pandas
读取 CSV
python
import pandas as pd
df = pd.read_csv('score.csv')
读取 Excel
python
df = pd.read_excel('test.xlsx')
👍 数据分析场景最强工具
最佳实践建议
- 优先使用
python
with open(...) as f:
- 路径拼接用:
python
os.path.join()
- 大文件避免:
python
read()
- 数据处理优先:
👉 pandas