You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无需os.path.join:求可直接返回完整路径的Python目录遍历工具包

实现直接获取完整文件路径的方案

标准库方案:pathlib

Python 3.4+ 自带的pathlib模块就能完美满足需求,它是面向对象的文件路径处理工具,用法简洁:

from pathlib import Path

top = '~/folder'
# expanduser用于解析路径中的~符号
for file_path in Path(top).expanduser().iterdir():
    full_file_path = file_path  # 直接就是完整路径的Path对象,转字符串用str(file_path)

如果需要筛选仅文件(排除目录),可添加判断:

from pathlib import Path

top = '~/folder'
for file_path in Path(top).expanduser().iterdir():
    if file_path.is_file():
        print(str(file_path))

标准库方案:glob

另一个标准库glob也能直接返回完整路径,还支持通配符匹配:

import glob
import os

top = os.path.expanduser('~/folder')
# 获取目录下所有项的完整路径
for full_file_path in glob.glob(os.path.join(top, '*')):
    print(full_file_path)

自定义封装(按需使用)

如果偏好完全贴合你想要的调用形式,也可以自己封装一个简单函数:

import os

def listdir(top):
    top = os.path.expanduser(top)
    for file in os.listdir(top):
        yield os.path.join(top, file)

# 调用示例
top = '~/folder'
for full_file_path in listdir(top):
    print(full_file_path)

内容的提问来源于stack exchange,提问作者mkohler

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:15:20