前面分享了数据类型、运算、三大结构、函数,相信您已经能用Python做很多事情了。
但你发现没有:
程序一关闭,输入的数据全没了
想保存计算结果到电脑里?做不到
想读取电脑上的文本、CSV、配置?不会
这时候,你就需要文件操作了!
文件操作,就是让Python程序能够和电脑硬盘上的文件打交道——读取、写入、追加、创建、删除。
一、文件是什么?(Python视角)
在Python看来,一个文件就是一串字符序列(文本文件)或者字节序列(二进制文件)。
今天主要讲文本文件操作,最常用、最好上手。
二、文件操作三步走
Python文件操作有一个经典口诀:
1️⃣ 打开文件 —— open()
2️⃣ 读/写文件 —— read() / write()
3️⃣ 关闭文件 —— close()
类比案例:就像用冰箱:打开冰箱门 → 放东西/取东西 → 关上冰箱门
三、打开文件:open() 函数
基本语法
f =open("文件名","模式", encoding="编码")
常用模式(重点)
加上 'b' 就是二进制模式
f =open("图片.jpg","rb")# 读取二进制f =open("音乐.mp3","wb")# 写入二进制
💡 编码很重要:中文文件一般用 encoding="utf-8",否则可能乱码。
四、读取文件(详细拆解)
准备一个示例文件 demo.txt
第一行:Hello Python
第二行:你好,世界
第三行:文件操作真有趣
1️⃣ read() —— 读取全部
f =open("demo.txt","r", encoding="utf-8")content = f.read()print(content)f.close()
输出:
第一行:Hello Python
第二行:你好,世界
第三行:文件操作真有趣
2️⃣ read(size) —— 读取指定字节数
f =open("demo.txt","r", encoding="utf-8")content = f.read(10)# 读10个字符print(content)# 第一行:Helf.close()
3️⃣readline() —— 读取一行
f =open("demo.txt","r", encoding="utf-8")line1 = f.readline()line2 = f.readline()print(f"第一行:{line1}")print(f"第二行:{line2}")f.close()
4️⃣ readlines() —— 读取所有行,返回列表
f =open("demo.txt","r", encoding="utf-8")lines = f.readlines()print(lines)# ['第一行:Hello Python\n', '第二行:你好,世界\n', ...]f.close()
5️⃣ 最推荐的方式:直接遍历文件对象
f =open("demo.txt","r", encoding="utf-8")for line in f: print(line.strip())# strip() 去掉换行符f.close()
五、写入文件
1️⃣ write() 模式(会清空原内容)
f =open("output.txt","w", encoding="utf-8")f.write("这是第一行\n")f.write("这是第二行\n")f.write("这是第三行")f.close()
⚠️ 注意:'w' 模式会把原有内容全部清空!小心操作。
2️⃣ append() 模式(追加到末尾)
f =open("output.txt","a", encoding="utf-8")f.write("\n这是追加的一行")f.close()
3️⃣ 写入多行数据
lines =["苹果","香蕉","橙子"]f =open("fruits.txt","w", encoding="utf-8")for fruit in lines: f.write(fruit +"\n")f.close()
六、with 语句(最佳实践)
每次都要手动 close(),忘记关了怎么办?
Python 提供了 with 语句,自动帮你关闭文件!
# 推荐写法with open("demo.txt","r", encoding="utf-8") as f: content = f.read() print(content)# 这里文件已经自动关闭了,不需要 f.close()
优点:
自动关闭文件,不用记 close()
即使中间出错也会正确关闭
代码更简洁
# 读取文件的标准写法with open("input.txt","r", encoding="utf-8") as f: for line in f: process(line)# 写入文件的标准写法 with open("output.txt","w", encoding="utf-8") as f: f.write("Hello World")
💡 记住:以后所有文件操作,都用 with!
七、操作文件和目录(os 模块)
除了读写文件内容,还经常需要操作文件本身(重命名、删除、判断存在等)。
常用操作
# 1. 检查文件/目录是否存在if os.path.exists("demo.txt"): print("文件存在")# 2. 判断是不是文件if os.path.isfile("demo.txt"): print("是文件")# 3. 判断是不是目录if os.path.isdir("my_folder"): print("是目录")# 4. 重命名文件os.rename("old.txt","new.txt")# 5. 删除文件os.remove("to_delete.txt")# 6. 创建目录os.mkdir("新建文件夹")# 7. 删除空目录os.rmdir("空文件夹")# 8. 获取当前工作目录current = os.getcwd()print(current)# 9. 列出目录下的所有文件files = os.listdir(".")print(files)# 10. 拼接路径(跨平台兼容)path = os.path.join("folder","subfolder","file.txt")
八、pathlib 模块(更现代的方式)
Python 3.4+ 推荐使用 pathlib,比 os 更优雅。
from pathlib import Path# 创建路径对象p = Path("demo.txt")# 读取文件content = p.read_text(encoding="utf-8")# 写入文件p.write_text("Hello Pathlib", encoding="utf-8")# 检查是否存在if p.exists(): print("存在")# 获取文件名、后缀、父目录print(p.name)# demo.txtprint(p.stem)# demoprint(p.suffix)# .txtprint(p.parent)# .(父目录)# 遍历目录for file in Path(".").glob("*.txt"): print(file)
pathlib 用起来更直观,推荐掌握!
九、实战案例
案例1:复制文件
def copy_file(src, dst): """复制文件""" with open(src,"r", encoding="utf-8")as f_src: content = f_src.read() with open(dst,"w", encoding="utf-8")as f_dst: f_dst.write(content) print(f"复制成功:{src} → {dst}")copy_file("source.txt","target.txt")
案例2:统计文件字数
def word_count(filename): """统计文本文件中的字符数、单词数、行数""" with open(filename,"r", encoding="utf-8")as f: content = f.read() lines = content.splitlines() words = content.split() char_count =len(content) word_count =len(words) line_count =len(lines) print(f"文件:{filename}") print(f"字符数:{char_count}") print(f"单词数:{word_count}") print(f"行数:{line_count}") return char_count, word_count, line_count word_count("demo.txt")
案例3:登录注册系统(文件存用户数据)
import hashlib USER_FILE ="users.txt"def hash_password(password): """对密码进行简单加密(实际生产环境请用bcrypt等)""" return hashlib.sha256(password.encode()).hexdigest()def register(username, password): """注册新用户""" # 检查用户是否已存在 with open(USER_FILE,"a+", encoding="utf-8")as f: f.seek(0)# 移动指针到开头 for line in f: if line.startswith(username +":"): return False,"用户名已存在" # 写入新用户 hashed = hash_password(password) f.write(f"{username}:{hashed}\n") return True,"注册成功"def login(username, password): """用户登录""" with open(USER_FILE,"r", encoding="utf-8")as f: hashed = hash_password(password) for line in f: stored_user, stored_pwd = line.strip().split(":") if stored_user == username and stored_pwd == hashed: return True,"登录成功" return False,"用户名或密码错误"# 测试print(register("小明","123456"))# (True, '注册成功')print(login("小明","123456"))# (True, '登录成功')print(login("小明","wrong"))# (False, '用户名或密码错误')
案例4:CSV文件读写(常用数据格式)
import csv# 写入CSVwithopen("students.csv","w", encoding="utf-8", newline="")as f: writer = csv.writer(f) writer.writerow(["姓名","年龄","成绩"]) writer.writerow(["张三",18,85]) writer.writerow(["李四",19,92]) writer.writerow(["王五",18,78])# 读取CSVwithopen("students.csv","r", encoding="utf-8")as f: reader = csv.reader(f)for row in reader:print(row)# 输出:# ['姓名', '年龄', '成绩']# ['张三', '18', '85']# ['李四', '19', '92']# ['王五', '18', '78']
案例5:配置文件读写(保存程序设置)
import json# 保存配置config ={"theme":"dark","font_size":14,"auto_save":True,"last_user":"小明"}with open("config.json","w", encoding="utf-8")as f: json.dump(config, f, indent=4, ensure_ascii=False)# 读取配置with open("config.json","r", encoding="utf-8")as f: loaded_config = json.load(f) print(loaded_config["theme"])# dark
十、常见错误与避坑指南
🔥 坑1:忘记指定编码(中文乱码)
# ❌ 不指定编码,Windows上可能用GBK,中文乱码withopen("中文.txt","r")as f: content = f.read()# 乱码!# ✅ 明确指定 utf-8withopen("中文.txt","r", encoding="utf-8")as f: content = f.read()
🔥 坑2:'w' 模式不小心清空了文件
# 危险!文件会被清空with open("important.txt","w")as f: # 如果不小心写错了,内容全没了 pass# 想保留原内容用 'a' 或先判断if os.path.exists("important.txt"): print("文件存在,是否覆盖?")
🔥 坑3:读取后忘记关闭(资源泄露)
# ❌ 忘了关闭f =open("file.txt","r")data = f.read()# 忘记 f.close()# ✅ 用 with 自动关闭with open("file.txt","r")as f: data = f.read()
🔥 坑4:路径问题(找不到文件)
# ❌ 使用反斜杠(Windows上可能出问题)with open("C:\new\file.txt","r")as f:# \n 会被解析成换行符# ✅ 三种正确写法with open("C:/new/file.txt","r")as f:# 正斜杠with open(r"C:\new\file.txt","r")as f:# 原始字符串with open("C:\\new\\file.txt","r")as f:# 双反斜杠
🔥 坑5:读取文件后指针位置
withopen("file.txt","r")as f: content1 = f.read()# 读完,指针在末尾 content2 = f.read()# 再读,得到空字符串 f.seek(0)# 把指针移回开头 content3 = f.read()# 又能读到了
十一、速查表
| |
|---|
| with open(f, 'r', encoding='utf-8') as f: data = f.read() |
| for line in f: |
| with open(f, 'w', encoding='utf-8') as f: f.write('hi') |
| with open(f, 'a', encoding='utf-8') as f: f.write('hi') |
| os.path.exists('file.txt') |
| os.remove('file.txt') |
| os.rename('old','new') |
| csv.reader() |
| csv.writer() |
| json.load(f) |
| json.dump(data, f) |
| os.getcwd() |
| os.listdir('.') |
| from pathlib import Path |
写在最后
文件操作是Python程序的记忆能力。
学会了它,你的程序就能:
保存用户数据(登录、配置、进度)
处理各种文件(日志、报表、CSV)
和其他软件交换数据(JSON、TXT)
📌 如果觉得有用,点赞+在看+转发 给正在学Python的小伙伴!
文件在手,数据永久。我们下期见! 👋