Python文件操作详解:从文件读写到os、shutil模块实战

一、什么是文件?

在计算机中,文件(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

main.py

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异常处理
  • 模块和包
  • 爬虫数据保存
  • 数据分析文件处理

文件操作是Python从基础语法进入实际开发的重要一步。

相关推荐
RS迷途小书童1 小时前
Python 解析大疆无人机 SRT 字幕日志
开发语言·python·无人机
我不会起名字3221 小时前
一天一道算法题(29):单调栈
java·数据结构·python·算法·leetcode·golang·单调栈
萧鼎1 小时前
2026新库实测:sbxloop 1.5.24 让 AI Agent 在 Docker 沙箱中安全自治,告别环境混乱
人工智能·python·开源·开发工具·ai agent
点心的游戏开发世界1 小时前
GDScript 入门笔记(十六):文件读写与数据持久化
开发语言·笔记·游戏引擎·godot
栀椩1 小时前
CODrone 无人机航拍车辆检测
pytorch·python·yolo
会飞的拖把2 小时前
Python序列详解:列表、元组、字符串的通用操作(超详细版)
开发语言·windows·python
2601_962283882 小时前
如何通过python控制nbiot
python·串口通信·数据传输·nb-iot·at命令
reasonsummer2 小时前
【办公类-115-01】20260906育儿知识(家园小报)批量制作(2026年9月-2027年6月)
开发语言·数据库·c#
君顾12 小时前
智慧场馆解决方案小程序系统实战:从架构设计到上线指南
java·开发语言·智慧场馆