Python中优雅的处理文件路径

写代码(尤其是脚本的时候)经常会遇到要处理文件路径的问题,通常有这么几个考量:

  • 简单易懂
  • 跨平台(Unix使用 / 而Windows使用 \
  • 容易拼接

个人此前最常用的就是 os.path.join 了,现在介绍一种更直观更高端的方式,那就是pathlib里的 Path

In [1]: from pathlib import Path  # 首先导入Path

In [2]: current_path = Path(".")  # 获取当前路径

In [3]: current_path.home()  # 打印家目录的路径
Out[3]: PosixPath('/home/jiajun')

In [4]: current_path.resolve()  # 获取绝对路径
Out[4]: PosixPath('/home/jiajun/Code/blog')

In [5]: current_path.glob("*.py")  # 使用glob来匹配文件或者文件夹
Out[5]: <generator object Path.glob at 0x7f88b533a840>

In [6]: [i for i in current_path.glob("*.py")]
Out[6]:
[PosixPath('config.py'),
 PosixPath('gen_catalog.py'),
 PosixPath('utils.py'),
 PosixPath('models.py')]

In [7]: fake_path = current_path / "helloworld"  # 使用 / 来增加层级,是不是比 os.path.join 好看些

In [8]: fake_path.resolve()
Out[8]: PosixPath('/home/jiajun/Code/blog/helloworld')

In [9]: fake_path.exists()  # 判断是否存在
Out[9]: False

通过上述操作可以看出来,Path 的操作比 os.path 中的操作简单明了的多,上面只是其中一部分操作, 全面的 osos.path 中的操作 和 pathlib 中的操作的对比表格 在这里


参考资料:


更多文章
  • 读《为什么学生不喜欢上学》
  • OpenAI Prompt Engineering 摘录和总结
  • 读《打造真正的新产品》
  • 2023年终总结
  • VueJS 总结
  • Linux 自动挂载 alist 提供的webdav
  • FreeBSD 使用 vm-bhyve 安装Debian虚拟机
  • FreeBSD 和 Linux 网卡聚合实现提速
  • GPT 帮我搞定了时区转换问题
  • 长任务系统如何处理?
  • macOS/Linux 编译 InputLeap
  • 使用开源软KVM - synergy-core
  • 解决 macOS 终端hostname一直变化问题
  • KVM 共享 Intel 集成显卡
  • PromQL 备忘