第 21 章 / 70 · 基础 · 常用标准库
os 模块
文件与目录操作
先介绍1 个 demo6 个任务答案可展开
一、本章介绍
os 用来操作文件系统:getcwd 当前目录、listdir 列目录、path.join 拼路径、path.exists 判断存在、makedirs 建目录。
这一章从路径拼接到文件遍历,所有例子在临时目录运行。
本章要点
- getcwd / listdir
- path.join 拼路径
- path.exists 判断
- path.splitext 取扩展名
二、先看 demo
下面这个例子把本章涉及的用法尽量全面地串了一遍,代码带逐行注释,可以直接复制到本地 .py 文件运行。
案例
先看一个完整例子
介绍 · 逐行注释import os
p=os.path.join("data","a.txt")
print(p)
print(os.path.exists(p))
print(os.path.splitext(p)[1])
for name in ["a.txt","b.py"]:
open(name,"w").close()
print(sorted(os.listdir("."))[:2])运行结果
data\a.txt
False
.txt
['a.txt', 'b.py']要点:用 os.path.join 拼路径(自动处理斜杠),splitext 取扩展名,listdir 列目录。
三、6 个任务(自己先写,再看答案)
难度从入门到挑战逐步增加。每个任务的答案默认折叠,点开可看参考代码、运行结果;有第二种解法的也一并给出。代码都可以直接运行。
任务 1
拼路径
自己写 · 附答案入门 ★☆☆解题提示:本题主要用到 getcwd / listdir、path.join 拼路径、path.exists 判断。先对照要求自己写一遍,卡住了再展开答案。
用 os.path.join 拼 "dir" 和 "file.txt"
参考答案(先自己写,再看)
参考答案一
import os
print(os.path.join("dir","file.txt"))运行结果
dir\file.txt参考答案二(另一种解法)
import os
print(os.path.join("dir")+"\\file.txt")任务 2
取扩展名
自己写 · 附答案入门 ★☆☆解题提示:本题主要用到 getcwd / listdir、path.join 拼路径、path.exists 判断。先对照要求自己写一遍,卡住了再展开答案。
取 "photo.jpg" 的扩展名
参考答案(先自己写,再看)
参考答案一
import os
print(os.path.splitext("photo.jpg")[1])运行结果
.jpg参考答案二(另一种解法)
print("."+"photo.jpg".split(".")[-1])任务 3
判断存在
自己写 · 附答案进阶 ★★☆解题提示:本题主要用到 getcwd / listdir、path.join 拼路径、path.exists 判断。先对照要求自己写一遍,卡住了再展开答案。
判断 "nope.txt" 是否存在
参考答案(先自己写,再看)
参考答案一
import os
print(os.path.exists("nope.txt"))运行结果
False参考答案二(另一种解法)
import os
print(os.path.isfile("nope.txt"))任务 4
创建文件并列出
自己写 · 附答案进阶 ★★☆解题提示:本题主要用到 getcwd / listdir、path.join 拼路径、path.exists 判断。先对照要求自己写一遍,卡住了再展开答案。
创建 "test.txt" 后判断它存在
参考答案(先自己写,再看)
参考答案一
import os
open("test.txt","w").close()
print(os.path.exists("test.txt"))运行结果
True参考答案二(另一种解法)
import os
with open("t2.txt","w") as f: pass
print(os.path.isfile("t2.txt"))任务 5
按扩展名分组
自己写 · 附答案挑战 ★★★解题提示:本题主要用到 getcwd / listdir、path.join 拼路径、path.exists 判断。先对照要求自己写一遍,卡住了再展开答案。
把 ["a.txt","b.py","c.txt"] 按扩展名分组统计
参考答案(先自己写,再看)
参考答案一
import os
d={}
for f in ["a.txt","b.py","c.txt"]:
e=os.path.splitext(f)[1]
d[e]=d.get(e,0)+1
print(d)运行结果
{'.txt': 2, '.py': 1}参考答案二(另一种解法)
from collections import Counter
import os
print(dict(Counter(os.path.splitext(f)[1] for f in ["a.txt","b.py","c.txt"])))任务 6
临时目录文件数
自己写 · 附答案挑战 ★★★解题提示:本题主要用到 getcwd / listdir、path.join 拼路径、path.exists 判断。先对照要求自己写一遍,卡住了再展开答案。
在临时目录建 3 个文件后统计 .txt 文件数
参考答案(先自己写,再看)
参考答案一
import os
for n in ["x.txt","y.txt","z.py"]: open(n,"w").close()
files=["x.txt","y.txt","z.py"]
print(sum(1 for f in files if f.endswith(".txt")))运行结果
2参考答案二(另一种解法)
import os
print(len([f for f in ["x.txt","y.txt","z.py"] if f.endswith(".txt")]))