Python零基础入门(七):文件操作
写了个脚本跑了3小时,结果忘了存。
下次开机,全没了。这种事干一次就够了。
一、读写三件套
写入用open()打开文件,指定'w'模式和编码,write()逐行写:
with open("output.txt", "w", encoding="utf-8") as f: f.write("第一行\n") f.write("第二行\n")
读取用'r'模式,read()一次性把内容拉进字符串:
with open("output.txt", "r", encoding="utf-8") as f: content = f.read() print(content)
大文件别用read(),直接迭代——不炸内存:
with open("data.txt", "r", encoding="utf-8") as f: for line in f: print(line.strip())
二、打开模式速查
踩坑警告:'w'会直接清空原文件!想保留旧数据,用'a'。
三、with语句(必须用)
# 反面教材:忘了close就完蛋f = open("data.txt", "r")content = f.read()f.close()# 正确姿势:离开with块自动关闭,异常也不怕with open("data.txt", "r") as f: content = f.read()
三个好处:自动关闭、异常安全、代码更短。
四、os模块:路径和目录
路径拼接——别手写斜杠,os.path.join()跨平台兼容:
import ospath = os.path.join("data", "files", "test.txt")
拆路径——取文件名、取目录、判断存在:
print(os.path.basename("/home/user/test.txt")) # test.txtprint(os.path.dirname("/home/user/test.txt")) # /home/userprint(os.path.exists("/tmp/test.txt")) # True/False
目录操作——创建、列出、遍历:
os.makedirs("a/b/c", exist_ok=True) # 创建多级目录files = os.listdir(".") # 列出当前目录for root, dirs, files in os.walk("my_project"): print(f"目录:{root},文件:{files}")
文件操作——重命名、复制、删除:
import shutilos.rename("old.txt", "new.txt")shutil.copy("source.txt", "dest.txt")os.remove("file.txt")
五、三个实用函数
统计文件行数、词数、字符数,像Linux的wc命令:
def count_file(filename): with open(filename, "r", encoding="utf-8") as f: lines = f.readlines() return len(lines), sum(len(l.split()) for l in lines), sum(len(l) for l in lines)lines, words, chars = count_file("example.txt")print(f"行数:{lines},单词:{words},字符:{chars}")
安全写入——文件已存在就自动加后缀,避免覆盖:
def safe_write(filename, content): import os if not os.path.exists(filename): with open(filename, "w", encoding="utf-8") as f: f.write(content) return filename name, ext = os.path.splitext(filename) counter = 1 while os.path.exists(f"{name}_{counter}{ext}"): counter += 1 new_name = f"{name}_{counter}{ext}" with open(new_name, "w", encoding="utf-8") as f: f.write(content) return new_name
读取配置文件——解析key=value格式,跳过注释和空行:
def read_config(filename): config = {} with open(filename, "r", encoding="utf-8") as f: for line in f: line = line.strip() if not line or line.startswith("#"): continue if "=" in line: key, value = line.split("=", 1) config[key.strip()] = value.strip() return config
下一篇预告:Pillow图片处理——Python也能批量处理图片。