Python命令行工具:获取文件与目录的优雅实现问询
更优雅的
get_files实现方案 方案1:使用pathlib(推荐,Python3.4+)
pathlib是Python官方推荐的路径处理库,面向对象的API比传统os模块更简洁直观,能轻松替代嵌套循环:
from pathlib import Path def get_files(sources): result = [] for src in sources: path = Path(src) if path.is_file(): result.append(str(path)) elif path.is_dir(): # 遍历目录下所有直接子文件(非递归) result.extend(str(item) for item in path.iterdir() if item.is_file()) return result
如果需要递归遍历所有子目录中的文件,把path.iterdir()换成path.rglob('*')即可:
def get_files(sources): result = [] for src in sources: path = Path(src) if path.is_file(): result.append(str(path)) elif path.is_dir(): # 递归遍历所有子文件 result.extend(str(item) for item in path.rglob('*') if item.is_file()) return result
方案2:极简列表推导式
如果追求极致简洁,用嵌套列表推导式可以把逻辑压缩到一行,同时保持可读性:
from pathlib import Path def get_files(sources): return [ str(path) for src in sources for path in ( [Path(src)] if Path(src).is_file() else (p for p in Path(src).iterdir() if p.is_file()) ) ]
示例验证
针对你的输入['file.txt', 'dir/'],调用get_files会返回预期结果:
>>> get_files(['file.txt', 'dir/']) ['file.txt', 'dir/file1.txt', 'dir/file2.txt', 'dir/file3.txt']
为什么这更Pythonic?
- 用
pathlib替代手动拼接路径,避免字符串操作的潜在错误 - 用生成器表达式/列表推导替代多层嵌套循环,代码更紧凑易读
- 明确区分文件和目录的处理逻辑,符合Python"显式优于隐式"的设计原则
内容的提问来源于stack exchange,提问作者dbran
相关产品推荐
相关产品推荐

