第9讲 · 路径与目录操作

路径与目录操作

理解路径的起点、拼接、目录查看与安全创建。

1重点函数的完整语法
2每个函数单独演示
3真实路径与目录树同步对照

文件、文件夹与真实位置

1文件:一份具体资料,如notes.txt
2文件夹:容纳文件和子文件夹
3路径:说明目标在哪里

语法拆解

notes.txt
文件名,只说明叫什么
materials/notes.txt
相对路径,还说明它在materials中

绝对路径、相对路径与当前工作目录

1绝对路径从系统根位置写起
2相对路径从当前工作目录写起
3当前工作目录不一定是脚本所在目录

语法拆解

"/tmp/lesson09_workspace/materials/notes.txt"
从根位置写起的绝对路径
"materials/notes.txt"
从当前工作目录出发
"."
表示当前工作目录

import os 与 os.getcwd()

l09_getcwd.py
cwd = os.getcwd()
print("当前工作目录:", cwd)
print("目标文件夹:", os.path.join(cwd, "materials"))
import os
导入Python标准库中的os模块
cwd = os.getcwd()
无参数调用,返回当前工作目录字符串
1调用形式:函数括号中不需要参数
2返回值:当前工作目录的字符串
3作用:只读取位置,不创建文件

os.path.join():拼出目标路径

l09_join_path.py
import os

workspace = "/tmp/lesson09_workspace"
folder = os.path.join(workspace, "materials")
target = os.path.join(folder, "notes.txt")

print("当前工作目录:", workspace)
print("目标文件夹:", folder)
print("目标文件:", target)
folder = os.path.join(workspace, "materials")
拼出materials文件夹的完整路径
target = os.path.join(folder, "notes.txt")
再拼出notes.txt的完整路径
1参数:依次传入起点、文件夹名和文件名
2返回值:拼好的路径字符串
3作用:只组合路径,不创建目标

os.listdir():查看目录内容

l09_listdir.py
names = sorted(os.listdir(folder))
print("正在读取:", folder)
print("目录内容:", names)
for name in names:
    print("│─", name)
os.listdir("materials")
查看指定目录
os.listdir(".")
查看当前工作目录
for name in names:
逐项取出名称
1参数:要查看的文件夹路径
2返回值:目录中的名称列表
3作用:只读取名称,不修改文件

exists、isfile、isdir:三问分清类型

l09_path_state.py
for label, path in [("目录", folder), ("文件", file_path), ("缺失", missing)]:
    print(label, os.path.exists(path),
          os.path.isfile(path), os.path.isdir(path))
os.path.exists(path)
这条路径存在吗
os.path.isfile(path)
它是普通文件吗
os.path.isdir(path)
它是文件夹吗
1共同参数:要判断的路径字符串
2返回值:True或False
3三个函数的问题不同,不能互相代替

os.makedirs():创建多级目录

l09_makedirs.py
os.makedirs(target, exist_ok=True)
os.makedirs(target, exist_ok=True)
print("创建位置:", target)
print("目标是目录:", os.path.isdir(target))
print("上级列表:", sorted(os.listdir(os.path.dirname(target))))
os.makedirs(target, exist_ok=True)
递归创建target及缺失的上级目录
os.path.isdir(target)
创建后检查目标是否真的是目录
1第1个参数:要创建的目标路径
2关键字参数:exist_ok=True允许已有目录
3副作用:真正改变目录结构

exist_ok=True 的边界:同名文件

l09_conflict_guard.py
print("目标路径:", target)
if os.path.exists(target) and not os.path.isdir(target):
    print("停止:同名路径是文件")
else:
    os.makedirs(target, exist_ok=True)
os.path.exists(target)
先看目标是否存在
os.path.isdir(target)
再确认是否为目录
os.makedirs(target, exist_ok=True)
只对已有目录容错
1已有目录可以重复准备
2同名路径如果是文件,创建目录仍会失败
3操作前用isdir确认目标类型

应用示例:准备三个练习目录

l09_short_application.py
base = os.path.join(workspace, "practice")
os.makedirs(base, exist_ok=True)
for i in range(1, 4):
    child = os.path.join(base, "lesson_0" + str(i))
    os.makedirs(child, exist_ok=True)
print("目标文件夹:", base)
print("目录内容:", sorted(os.listdir(base)))
1join组成目标路径,makedirs负责创建
2for只重复三次,目录名逐一生成
3isdir与listdir核对实际结果

本讲总结:五个函数,一条安全流程

1确认起点:os.getcwd()
2拼出路径:os.path.join()
3读取目录:os.listdir()
4判断类型:exists、isfile、isdir
5安全创建:os.makedirs(),完成后再次核对

语法拆解

先确认位置
读取当前工作目录,明确相对路径的起点
再读取与判断
查看目录内容,分清文件、文件夹和不存在路径
最后执行创建
只有目标位置与类型确认无误,才调用makedirs
课堂 Python 解释器
点击“逐步运行”后,这里会显示结果。
Python:按执行步骤显示结果。