刚学Python的同学,是不是写文件操作总踩各种坑?
要么路径写错报FileNotFoundError,要么忘记关文件导致资源泄漏,读写中文还经常遇到乱码问题。
🔍 1、基础用法:先搞懂open函数的核心参数
Python操作文件的入口就是内置的open()函数,核心参数其实就3个,记下来就不会错。
📌 必传的3个核心参数
- file
- mode:操作模式,读(r)、写(w)、追加(a)是最常用的
- encoding:编码格式,Windows上建议固定写
utf-8避免乱码
最基础的读取写法是这样的:
# 打开文件 f = open("demo.txt", "r", encoding="utf-8") # 读取全部内容 content = f.read() print(content) # 必须手动关闭文件 f.close()
注意:这种写法如果中间代码报错,会导致f.close()不执行,资源一直被占用,不推荐生产环境用。
💡 2、最佳实践:用上下文管理器自动处理资源
Python官方推荐的写法是用with上下文管理器,不需要手动关文件,代码更简洁也更安全。
📝 读取文件的3种常用方式
根据文件大小选不同的读取方法,避免大文件把内存撑爆:
逐行读取大文件的标准写法:
with open("large_file.txt", "r", encoding="utf-8") as f: # 每次只加载一行到内存 for line in f: # 去掉每行末尾的换行符 line = line.strip() if line: # 跳过空行 print(line)
✍️ 写入文件的两种模式
写入前要注意mode参数的区别,别把原有文件覆盖了:
w模式:覆盖写入,文件不存在会自动创建,存在就清空原有内容a模式:追加写入,在文件末尾添加内容,不会覆盖原有数据
# 覆盖写入 with open("output.txt", "w", encoding="utf-8") as f: f.write("第一行内容\n") f.write("第二行内容\n") # 一次性写入多行 lines = ["第三行\n", "第四行\n"] f.writelines(lines)
⚡ 3、常见场景实战:拿来就能用的代码片段
整理了3个日常开发最常用的文件操作场景,直接复制就能用。
🎯 场景1:读写JSON配置文件
import json # 读取JSON配置 with open("config.json", "r", encoding="utf-8") as f: config = json.load(f) print(config["version"]) # 写入JSON配置,indent参数美化格式 with open("config.json", "w", encoding="utf-8") as f: json.dump(config, f, indent=2, ensure_ascii=False)
🎯 场景2:统计代码文件行数
def count_code_lines(file_path): count = 0 with open(file_path, "r", encoding="utf-8") as f: for line in f: # 跳过空行和注释 stripped = line.strip() if stripped and not stripped.startswith("#"): count +=1 return count print(count_code_lines("main.py"))
🎯 场景3:合并多个TXT文件
import os # 合并当前目录下所有txt文件 with open("merged.txt", "w", encoding="utf-8") as out_f: for file_name in os.listdir("."): if file_name.endswith(".txt") and file_name != "merged.txt": with open(file_name, "r", encoding="utf-8") as in_f: out_f.write(in_f.read() + "\n")
📌 4、最后总结几个避坑点
- 操作文本文件一定指定
encoding="utf-8",避免跨平台乱码 - 大于100M的文件不要用
read()一次性读取,逐行迭代更安全
你平时用Python处理文件还有什么常见需求?评论区留言,下次给大家整理更多实用代码片段~