一、什么是文件?
在计算机中,文件(File)是存储在磁盘上的数据集合。
程序运行过程中产生的数据通常保存在:
- 内存
- 磁盘
其中:
- 内存中的数据:程序关闭后消失
- 磁盘中的数据:可以长期保存
将程序中的数据保存到磁盘文件中的过程叫:
数据持久化(Persistence)
例如:
python
name = "Tom"
print(name)
变量 name 保存在内存中。
程序结束:
Tom消失
如果保存:
python
with open("user.txt","w") as f:
f.write("Tom")
数据写入磁盘:
user.txt
Tom
下次程序运行仍然可以读取。
二、文件的分类
根据存储方式,文件可以分为:
1. 文本文件
文本文件:
使用字符编码保存的数据文件。
例如:
.txt
.py
.html
.csv
.json
内容:
hello python
你好
特点:
- 有统一编码格式
- 可以直接查看
常见编码:
| 编码 | 说明 |
|---|---|
| ASCII | 英文字符 |
| GB2312 | 简体中文 |
| GBK | 中文扩展 |
| UTF-8 | 最常用 |
Python默认推荐:
python
encoding="utf-8"
2. 二进制文件
二进制文件:
使用0和1保存的数据。
例如:
.jpg
.png
.mp4
.exe
.zip
.pdf
特点:
- 没有字符编码
- 人无法直接阅读
例如:
图片:
0101010101010101
Python操作二进制文件:
必须使用:
python
b模式
例如:
python
open("a.jpg","rb")
三、文件路径
文件路径用于定位文件。
Python支持:
- 相对路径
- 绝对路径
1. 相对路径
相对于当前程序位置。
例如:
项目:
PythonProject
main.py
test.txt
python
open("test.txt")
表示:
当前目录/test.txt
特殊符号:
当前目录
./
例如:
python
./test.txt
表示:
当前目录下test.txt。
上一级目录
../
例如:
python
../test.txt
表示:
上一级目录中的test.txt。
2. 绝对路径
从磁盘根目录开始。
Windows:
python
D:/Python/test.txt
Linux:
python
/home/user/test.txt
例如:
python
open("D:/data/test.txt")
四、open()打开文件
Python通过:
python
open()
打开文件。
基本语法:
python
open(file,mode,encoding)
例如:
python
f=open(
"test.txt",
"r",
encoding="utf-8"
)
返回:
文件对象
五、文件打开模式mode
1. r模式(读取)
默认模式:
python
open("test.txt","r")
特点:
- 只能读
- 文件必须存在
- 指针在开头
案例:
python
f=open(
"test.txt",
"r",
encoding="utf-8"
)
content=f.read()
print(content)
f.close()
2. w模式(写入)
python
open("test.txt","w")
特点:
文件不存在:
创建文件
文件存在:
清空原内容
例如:
原文件:
hello
代码:
python
f=open("test.txt","w")
f.write("python")
f.close()
结果:
python
原来的hello被删除。
3. a模式(追加)
append:
追加。
python
open("test.txt","a")
特点:
- 不删除原内容
- 写入末尾
例如:
原文件:
hello
代码:
python
f=open("test.txt","a")
f.write("\npython")
f.close()
结果:
hello
python
六、文件组合模式
r+
读写模式:
python
open("test.txt","r+")
特点:
- 文件必须存在
- 可以读写
- 不清空文件
w+
写读模式:
python
open("test.txt","w+")
特点:
- 可读
- 可写
- 清空文件
a+
追加读:
python
open("test.txt","a+")
特点:
- 可以读
- 可以追加
- 写入末尾
七、文本模式和二进制模式
文本模式
默认:
python
t
例如:
python
open("test.txt","rt")
二进制模式
使用:
python
b
例如:
读取图片:
python
open("a.jpg","rb")
写图片:
python
open("b.jpg","wb")
八、关闭文件
打开文件后:
python
f.close()
关闭。
例如:
python
f=open("test.txt")
data=f.read()
f.close()
但是推荐:
with上下文管理
python
with open(
"test.txt",
"r",
encoding="utf-8"
) as f:
data=f.read()
优点:
- 自动关闭文件
- 防止异常导致文件未关闭
实际开发推荐使用。
九、文件写入操作
1.write()
写入字符串。
例如:
python
with open(
"test.txt",
"w",
encoding="utf-8"
) as f:
f.write("hello python\n")
f.write("你好")
文件:
hello python
你好
2.writelines()
写入多个字符串。
参数:
必须是可迭代对象。
例如:
python
names=[
"张三\n",
"李四\n",
"王五"
]
with open(
"name.txt",
"w",
encoding="utf-8"
) as f:
f.writelines(names)
结果:
张三
李四
王五
3.print写入文件
print默认输出:
控制台。
可以修改:
python
print(
"hello",
file=f
)
例如:
python
with open(
"test.txt",
"w"
) as f:
print(
"Python",
file=f
)
十、文件读取操作
1.read()
读取全部内容。
python
with open(
"test.txt",
"r"
) as f:
data=f.read()
print(data)
指定读取长度:
python
f.read(5)
表示:
读取5个字符。
2.readline()
读取一行。
例如:
文件:
aaa
bbb
ccc
代码:
python
f.readline()
结果:
aaa
读取多行:
python
print(f.readline())
print(f.readline())
输出:
aaa
bbb
3.readlines()
一次读取所有行。
返回:
列表。
例如:
python
data=f.readlines()
print(data)
结果:
python
[
"aaa\n",
"bbb\n",
"ccc"
]
十一、文件指针
打开文件:
|
0
指针在开头。
读取:
python
f.read(5)
指针移动:
xxxxx|
再次读取:
从当前位置继续。
查看位置:
python
f.tell()
移动:
python
f.seek()
例如:
python
f.seek(0)
回到开头。
十二、文件拷贝案例
方法1:一次读取全部
python
def copyFile(src,dst):
with open(src,"rb") as source:
content=source.read()
with open(dst,"wb") as target:
target.write(content)
copyFile(
"a.jpg",
"b.jpg"
)
缺点:
如果文件很大:
10GB视频
↓
全部加载内存
容易内存不足。
方法2:分块复制(推荐)
python
def copyFile(src,dst):
with open(src,"rb") as source:
with open(dst,"wb") as target:
while True:
data=source.read(1024)
if not data:
break
target.write(data)
copyFile(
"a.mp4",
"b.mp4"
)
优势:
一次读取:
1024字节
不会占用大量内存。
十三、os模块文件操作
os:
Python操作系统接口模块。
作用:
- 文件夹操作
- 路径操作
- 文件判断
1.获取当前路径
python
import os
print(
os.getcwd()
)
2.创建目录
创建一级:
python
os.mkdir("test")
递归创建:
python
os.makedirs(
"a/b/c"
)
3.查看目录内容
python
os.listdir(".")
返回:
python
[
"a.txt",
"b.txt"
]
4.删除文件
python
os.remove(
"test.txt"
)
5.删除空目录
python
os.rmdir(
"test"
)
6.文件判断
是否存在:
python
os.path.exists(
"test.txt"
)
是否文件:
python
os.path.isfile(
"test.txt"
)
是否目录:
python
os.path.isdir(
"test"
)
7.获取文件信息
文件大小:
python
os.path.getsize(
"test.txt"
)
文件名:
python
os.path.basename(
"D:/test/a.txt"
)
结果:
a.txt
扩展名:
python
os.path.splitext(
"a.txt"
)
结果:
("a",".txt")
十四、shutil模块
shutil:
高级文件管理模块。
主要用于:
- 复制
- 移动
- 删除文件夹
1.复制文件
python
import shutil
shutil.copy(
"a.txt",
"b.txt"
)
2.复制并保留信息
python
shutil.copy2(
"a.txt",
"b.txt"
)
保留:
- 修改时间
- 权限
3.复制文件夹
python
shutil.copytree(
"old",
"new"
)
4.移动文件
python
shutil.move(
"a.txt",
"test/"
)
5.删除非空目录
os:
只能删除空目录。
shutil:
python
shutil.rmtree(
"test"
)
十五、os和shutil区别
| 模块 | 作用 |
|---|---|
| os | 操作系统、路径、目录 |
| shutil | 高级文件管理 |
简单记:
os:
在哪里?
有什么?
shutil:
复制
移动
删除
十六、综合案例:统计文件夹大小
python
import os
def get_size(path):
total=0
for root,dirs,files in os.walk(path):
for file in files:
filepath=os.path.join(
root,
file
)
total+=os.path.getsize(filepath)
return total
size=get_size(
"D:/test"
)
print(
"文件夹大小:",
size,
"字节"
)
十七、总结
Python文件操作是实际开发中非常重要的能力。
本文学习:
文件基础
- 文件分类
- 文件路径
- 文件编码
文件操作
- open()
- close()
- with
文件读写
- write()
- writelines()
- read()
- readline()
- readlines()
文件管理
os模块:
- 创建
- 删除
- 判断
- 路径处理
shutil模块:
- 复制
- 移动
- 删除文件夹
掌握文件操作以后,可以继续学习:
- Python异常处理
- 模块和包
- 爬虫数据保存
- 数据分析文件处理