(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)


相关推荐
点云-激光雷达-Slam-三维牙齿1 小时前
速度起飞 笔记本电脑6G显卡llama运行Qwen3.6 35BA3B MTP 大模型
人工智能·python·电脑·llama
言乐62 小时前
Python游戏水平测试辅助系统
开发语言·python·游戏·django·pygame
从零开始学习人工智能8 小时前
【踩坑实录】WSL2 解决 onnxruntime\-gpu ImportError: libcudart\.so\.13 无 CUDA13 运行库问题
python
卷无止境10 小时前
在 awesome-fastapi 里,哪些库值得一看?
后端·python
zhanghaha131410 小时前
Python进阶教程:6_JSON 数据解析 —— 新手完全指南
开发语言·python·json
Python私教10 小时前
API 输出模型怎么设计:从 model_dump() 到显式展示层
python·fastapi
Python私教11 小时前
本地 AI 工具服务该绑定 127.0.0.1 还是 0.0.0.0?
python·fastapi
卷无止境11 小时前
FastAPI 的Admin面板生态
后端·python
ctlover11 小时前
Streamlit 框架
python
ι:12 小时前
MATLAB 与 Python 搭建无人机地面站:优势、劣势与选型逻辑
python·matlab·无人机