(9)python开发经验

文章目录

      • [1 os.path.join()拼接路径](#1 os.path.join()拼接路径)
      • [2 条件变量](#2 条件变量)
      • [3 添加临时环境变量](#3 添加临时环境变量)

更多精彩内容
👉内容导航 👈
👉Qt开发 👈
👉python开发 👈

1 os.path.join()拼接路径

os.path.join() 是 Python 中处理文件路径拼接的核心函数,能自动适配不同操作系统的路径分隔符(如 Windows 的 \ 和 Linux/macOS 的 /)。以下是详细说明:


基本用法

python 复制代码
import os

path = os.path.join('dir1', 'dir2', 'file.txt')
# 输出结果(以 Linux 为例): 'dir1/dir2/file.txt'
# Windows 输出: 'dir1\\dir2\\file.txt'

核心规则

  1. 绝对路径会重置拼接

    • 如果某个参数是绝对路径(以 / 或盘符开头),则之前的路径会被丢弃
    python 复制代码
    os.path.join('dir1', '/dir2', 'file.txt')  # 结果: '/dir2/file.txt'
    os.path.join('C:\\Users', 'D:\\data', 'file.txt')  # 结果: 'D:\\data\\file.txt'(Windows)
  2. 空字符串处理

    • 空字符串参数会被忽略,但可能影响盘符(Windows):
    python 复制代码
    os.path.join('', 'dir1', '', 'file.txt')  # 结果: 'dir1/file.txt'
    os.path.join('C:', '', 'file.txt')        # 结果: 'C:file.txt'(Windows 下需注意!)
  3. 自动处理分隔符

    • 若参数末尾已有分隔符,不会重复添加:
    python 复制代码
    os.path.join('dir1/', 'dir2')  # 结果: 'dir1/dir2'

注意事项

  1. 不要手动拼接路径

    • ❌ 避免 path = 'dir1' + '/' + 'file.txt',因为跨平台兼容性差。
    • ✅ 始终使用 os.path.join()
  2. 处理空路径的风险

    • 空字符串可能导致意外结果:
    python 复制代码
    os.path.join('dir1', '', 'file.txt')  # 结果: 'dir1/file.txt'
  3. 特殊字符与非法字符

    • 如果路径包含非法字符(如 *?),函数不会报错,但后续文件操作可能失败:
    python 复制代码
    os.path.join('dir*', 'file?.txt')  # 合法拼接,但无法实际创建文件
  4. 跨平台行为差异

    • Windows 中处理盘符时需谨慎:
    python 复制代码
    os.path.join('C:/dir1', 'D:/dir2')  # 结果: 'D:/dir2'(丢弃前半部分)

最佳实践

  • 组合多个路径片段时

    python 复制代码
    base_dir = 'project'
    sub_dir = 'data'
    file_name = 'config.json'
    full_path = os.path.join(base_dir, sub_dir, file_name)
  • 处理用户输入路径时

    python 复制代码
    user_input = '/user/custom_path'  # 可能包含绝对路径
    safe_path = os.path.join('default_dir', user_input.lstrip('/'))

常见问题

Q:为什么拼接绝对路径时前面的路径被丢弃?

A:这是设计逻辑------绝对路径表示"根目录开始",因此会覆盖之前的相对路径。

Q:如何确保路径末尾有斜杠?

A:显式添加:

python 复制代码
dir_path = os.path.join('dir1', 'dir2') + os.sep  # 结果: 'dir1/dir2/'

2 条件变量

注意事项:

  1. 必须持有锁
    • 调用 wait()notify()notify_all() 前必须通过 acquire()with 语句获取锁。
python 复制代码
import threading

cond = threading.Condition()

# 等待
with cond:
    cond.wait()  # 等待
    
# 唤醒
with cond:
    cond.notify()  # 等待

3 添加临时环境变量

在代码中添加临时环境变量,便于访问指定路径下的内容;

python 复制代码
def __set_environ(self):
    """
    设置环境变量,将adb目录添加到PATH环境变量
    :return:
    """
    # 获取当前的PATH环境变量
    current_path = os.environ['PATH']
    # 新增路径到PATH环境变量
    adb_dir = get_adb_dir()
    if not os.path.exists(adb_dir):
        logger.error(f"adb目录 {adb_dir} 不存在")
        return
    os.environ['PATH'] = current_path + os.pathsep + str(adb_dir)


相关推荐
工业甲酰苯胺2 分钟前
Django集成Swagger全指南:两种实现方案详解
python·django·sqlite
豌豆花下猫17 分钟前
Python 潮流周刊#112:欢迎 AI 时代的编程新人
后端·python·ai
您的通讯录好友1 小时前
TechGPT2部署
linux·人工智能·python·大模型·techgpt
z are2 小时前
PyTorch 模型开发全栈指南:从定义、修改到保存的完整闭环
人工智能·pytorch·python
抠头专注python环境配置3 小时前
Pycharm、Python安装及配置小白教程
ide·python·pycharm
climber11214 小时前
【Python Web】一文搞懂Flask框架:从入门到实战的完整指南
前端·python·flask
都叫我大帅哥4 小时前
《线性回归:从入门到精通,一篇让你彻底搞懂的诙谐指南》
python·机器学习
都叫我大帅哥4 小时前
🚀 LangGraph终极指南:从入门到生产级AI工作流编排
python·langchain
山烛5 小时前
Python 数据可视化之 Matplotlib 库
开发语言·python·matplotlib·数据可视化
蛋仔聊测试5 小时前
SQL语句执行顺序全解析
python·面试