|
|
主要依靠 os 模块、pathlib 模块两种方式
一、os 模块(传统写法)
- import os
- path = "test.txt" # 替换你的路径
- # 1. 判断是否存在
- print(os.path.exists(path))
- # 2. 判断是否是 文件
- is_file = os.path.isfile(path)
- print("是文件:", is_file)
- # 3. 判断是否是 文件夹(目录)
- is_dir = os.path.isdir(path)
- print("是文件夹:", is_dir)
复制代码
常用 os 路径判断函数
os.path.exists(p):路径是否存在(文件 / 文件夹都返回 True)
os.path.isfile(p):仅普通文件返回 True
os.path.isdir(p):仅文件夹返回 True
os.path.islink(p):是否是软链接
二、pathlib 模块
- from pathlib import Path
- p = Path("test")
- print(p.exists()) # 是否存在
- print(p.is_file()) # 判断文件
- print(p.is_dir()) # 判断文件夹
- print(p.is_symlink()) # 判断软链接
复制代码
三、完整示例:自动区分
- from pathlib import Path
- def check_path(path):
- p = Path(path)
- if not p.exists():
- return "路径不存在"
- elif p.is_file():
- return "这是文件"
- elif p.is_dir():
- return "这是文件夹"
- else:
- return "其他类型(设备、管道等)"
- print(check_path("./demo"))
复制代码
四、遍历目录挨个判断内容类型
- import os
- folder = "./"
- for name in os.listdir(folder):
- full_path = os.path.join(folder, name)
- if os.path.isfile(full_path):
- print(f"文件:{name}")
- elif os.path.isdir(full_path):
- print(f"文件夹:{name}")
复制代码
|
|