Python教程25:文件操作基础
“磁盘是内存的延伸,文件是数据的归宿。”
程序经常需要读取配置文件、处理日志、保存数据。今天我们学习Python的文件操作,掌握数据持久化的基本技能。
1. 文件操作概述
为什么需要文件操作
内存vs文件:
- 内存(RAM):程序运行时的数据存储,速度快但程序结束后数据消失
- 文件(磁盘):永久存储数据,程序结束后数据保留
文件操作的应用场景:
- 读取配置文件(config.ini、settings.json)
- 处理日志文件(分析服务器日志)
- 数据持久化(保存用户数据)
- 批量处理(处理大量CSV、Excel文件)
- 网络爬虫(保存爬取的数据)
Python文件操作的三个步骤
1# 1. 打开文件
2file = open("example.txt", "r")
3
4# 2. 读取/写入文件
5content = file.read()
6
7# 3. 关闭文件
8file.close()
为什么要关闭文件:
- 释放系统资源
- 确保数据完全写入磁盘
- 避免文件被锁定
- 防止内存泄漏
2. 打开文件:open()函数
open()是Python的内置函数,用于打开文件:
1# open(file, mode='r', encoding=None)
2# - file: 文件路径
3# - mode: 打开模式
4# - encoding: 编码格式(文本文件需要指定)
5
6file = open("data.txt", "r", encoding="utf-8")
文件模式
| 模式 | 说明 | 文件必须存在 | 覆盖内容 |
|---|---|---|---|
'r' | 只读(默认) | 是 | - |
'w' | 只写 | 否(自动创建) | 是 |
'a' | 追加 | 否(自动创建) | 否 |
'x' | 独占创建 | 否(已存在报错) | - |
'r+' | 读写 | 是 | 否 |
'w+' | 读写 | 否(自动创建) | 是 |
'a+' | 读写追加 | 否(自动创建) | 否 |
二进制模式:在模式后加'b'
'rb':二进制只读'wb':二进制只写'ab':二进制追加
1# 文本模式(默认)
2text_file = open("data.txt", "r", encoding="utf-8")
3
4# 二进制模式(图片、视频等)
5image_file = open("photo.jpg", "rb") # 二进制不需要encoding
文件路径
1# 相对路径(相对于当前工作目录)
2file = open("data.txt") # 当前目录
3file = open("data/file.txt") # 子目录
4
5# 绝对路径
6file = open("/Users/username/data.txt") # macOS/Linux
7file = open("C:\\Users\\username\\data.txt") # Windows
8
9# 原始字符串(避免转义问题)
10file = open(r"C:\Users\username\data.txt")
11
12# 使用os.path或pathlib处理路径(推荐)
13import os
14file_path = os.path.join("data", "file.txt")
15file = open(file_path)
3. 读取文件
read() - 读取全部内容
1# read()读取整个文件
2# 适合小文件,大文件会占用大量内存
3with open("example.txt", "r", encoding="utf-8") as file:
4 content = file.read()
5 print(content)
6
7# read(size) - 读取指定字节数
8with open("example.txt") as file:
9 chunk = file.read(100) # 读取前100个字符
10 print(chunk)
readline() - 读取一行
1# readline()读取一行
2with open("example.txt") as file:
3 line = file.readline()
4 print(line)
5
6 # 读取多行
7 line1 = file.readline()
8 line2 = file.readline()
readlines() - 读取所有行
1# readlines()返回行列表
2# 每行是一个字符串(包含换行符\n)
3with open("example.txt") as file:
4 lines = file.readlines()
5 for line in lines:
6 print(line.strip()) # strip()去除换行符
逐行遍历(推荐)
1# 文件对象本身是迭代器
2# 逐行读取,内存高效,适合大文件
3with open("large_file.txt") as file:
4 for line in file:
5 print(line.strip())
性能对比:
1# 方法1:read() - 内存占用大
2content = file.read() # 一次性加载整个文件
3
4# 方法2:逐行迭代 - 内存高效
5for line in file: # 一次只加载一行
6 process(line)
4. 写入文件
write() - 写入字符串
1# write()写入字符串,返回写入的字符数
2with open("output.txt", "w", encoding="utf-8") as file:
3 file.write("Hello, World!\n")
4 file.write("Python文件操作\n")
5
6# 注意:write()不会自动添加换行符
writelines() - 写入多行
1# writelines()写入字符串列表
2# 不会自动添加换行符!
3lines = ["第一行\n", "第二行\n", "第三行\n"]
4
5with open("output.txt", "w", encoding="utf-8") as file:
6 file.writelines(lines)
追加模式
1# 'a'模式:在文件末尾追加内容
2with open("log.txt", "a", encoding="utf-8") as file:
3 file.write("新的日志记录\n")
5. with语句:上下文管理器
with语句是文件操作的最佳实践:
1# 不使用with:容易忘记关闭
2file = open("data.txt")
3try:
4 content = file.read()
5finally:
6 file.close() # 必须记得关闭
7
8# 使用with:自动关闭(推荐)
9with open("data.txt") as file:
10 content = file.read()
11# 离开with块时自动关闭文件
with的优势:
- 自动关闭文件,即使发生异常也会关闭
- 代码更简洁
- 避免资源泄漏
with是Python的上下文管理器协议:
- 实现
__enter__和__exit__方法的对象可以用with - 文件对象实现了这个协议
- 我们会在第27课详细学习上下文管理器
同时打开多个文件
1# Python 3.1+支持在一个with中打开多个文件
2with open("input.txt") as infile, open("output.txt", "w") as outfile:
3 content = infile.read()
4 outfile.write(content.upper())
6. 文件编码
为什么需要指定编码
文本文件在磁盘上是字节,需要编码/解码:
1# UTF-8:支持所有语言,推荐使用
2with open("chinese.txt", "w", encoding="utf-8") as file:
3 file.write("你好世界")
4
5# GBK:Windows中文系统默认
6with open("chinese.txt", "w", encoding="gbk") as file:
7 file.write("你好世界")
8
9# 不指定编码会使用系统默认(不推荐)
10# macOS/Linux: UTF-8
11# Windows: GBK/CP936
编码不匹配会导致乱码:
1# 用UTF-8写入
2with open("test.txt", "w", encoding="utf-8") as f:
3 f.write("你好")
4
5# 用GBK读取 - 乱码!
6with open("test.txt", "r", encoding="gbk") as f:
7 print(f.read()) # 可能显示乱码
最佳实践:
- 始终明确指定
encoding="utf-8" - 统一项目的编码格式
- 处理外部文件时先检测编码
7. 文件指针操作
文件对象维护一个"指针",标记当前读写位置:
1# tell() - 返回当前位置
2with open("data.txt") as file:
3 print(file.tell()) # 0(开始位置)
4 file.read(10)
5 print(file.tell()) # 10(读取了10个字符)
6
7# seek(offset, whence) - 移动指针
8# whence: 0=文件开头, 1=当前位置, 2=文件末尾
9with open("data.txt") as file:
10 file.seek(0) # 移到开头
11 file.seek(10) # 移到第10个字符
12 file.seek(0, 2) # 移到文件末尾
8. 二进制文件
处理图片、音频、视频等非文本文件:
1# 读取二进制文件
2with open("image.jpg", "rb") as file:
3 data = file.read()
4 print(type(data)) # <class 'bytes'>
5 print(len(data)) # 文件大小(字节)
6
7# 写入二进制文件
8with open("copy.jpg", "wb") as file:
9 file.write(data)
10
11# 复制文件
12with open("source.jpg", "rb") as src, open("dest.jpg", "wb") as dst:
13 dst.write(src.read())
9. 文件和目录操作
os模块
os是Python标准库,提供操作系统相关功能:
1import os
2
3# 检查文件是否存在
4if os.path.exists("file.txt"):
5 print("文件存在")
6
7# 获取文件大小
8size = os.path.getsize("file.txt")
9print(f"文件大小:{size}字节")
10
11# 删除文件
12os.remove("file.txt")
13
14# 重命名文件
15os.rename("old.txt", "new.txt")
16
17# 获取当前工作目录
18cwd = os.getcwd()
19print(f"当前目录:{cwd}")
20
21# 列出目录内容
22files = os.listdir(".")
23print(files)
24
25# 创建目录
26os.mkdir("new_folder")
27os.makedirs("parent/child/grandchild") # 递归创建
pathlib模块(Python 3.4+,推荐)
pathlib是现代的、面向对象的路径操作库:
1from pathlib import Path
2
3# 创建Path对象
4path = Path("data/file.txt")
5
6# 检查存在
7if path.exists():
8 print("文件存在")
9
10# 读取文件
11content = path.read_text(encoding="utf-8")
12
13# 写入文件
14path.write_text("内容", encoding="utf-8")
15
16# 获取文件信息
17print(path.name) # file.txt
18print(path.suffix) # .txt
19print(path.stem) # file
20print(path.parent) # data/
21
22# 遍历目录
23for file in Path(".").glob("*.txt"):
24 print(file)
10. 实用技巧
CSV文件处理
1import csv
2
3# csv模块是Python标准库
4# 专门用于处理CSV(逗号分隔值)文件
5
6# 写入CSV
7with open("data.csv", "w", newline="", encoding="utf-8") as file:
8 writer = csv.writer(file)
9 writer.writerow(["姓名", "年龄", "城市"])
10 writer.writerow(["张三", 25, "北京"])
11 writer.writerow(["李四", 30, "上海"])
12
13# 读取CSV
14with open("data.csv", encoding="utf-8") as file:
15 reader = csv.reader(file)
16 for row in reader:
17 print(row)
JSON文件处理
1import json
2
3# json模块用于处理JSON格式数据
4# JSON是Web开发中最常用的数据交换格式
5
6data = {
7 "name": "张三",
8 "age": 25,
9 "hobbies": ["读书", "旅游"]
10}
11
12# 写入JSON
13with open("data.json", "w", encoding="utf-8") as file:
14 json.dump(data, file, ensure_ascii=False, indent=2)
15
16# 读取JSON
17with open("data.json", encoding="utf-8") as file:
18 loaded_data = json.load(file)
19 print(loaded_data)
临时文件
1import tempfile
2
3# tempfile模块创建临时文件
4# 临时文件会在关闭后自动删除
5
6# 临时文件
7with tempfile.TemporaryFile(mode='w+') as temp:
8 temp.write("临时数据")
9 temp.seek(0)
10 print(temp.read())
11# 文件自动删除
12
13# 临时目录
14with tempfile.TemporaryDirectory() as tmpdir:
15 print(f"临时目录:{tmpdir}")
16 # 使用tmpdir
17# 目录自动删除
11. 小结
今天我们学习了Python文件操作:
- 基本流程:打开→读写→关闭
- open()函数:文件路径、模式、编码
- 读取:read()、readline()、readlines()、迭代
- 写入:write()、writelines()
- with语句:自动管理文件资源
- 编码:UTF-8、GBK,避免乱码
- 二进制文件:图片、音频、视频
- os/pathlib:文件和目录操作
- 特殊格式:CSV、JSON
文件操作是数据持久化的基础,掌握它能让你的程序处理真实世界的数据。
练习题:
- 写一个程序,统计文本文件的行数、单词数、字符数
- 实现文件复制功能,支持进度显示
- 读取CSV文件,按某列排序后写入新文件
本文代码示例:
关注公众号:极客老墨
更多 AI 应用开发、工程实践和效率工具分享,欢迎扫码关注。
