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


相关推荐
小途软件24 分钟前
用于机器人电池电量预测的Sarsa强化学习混合集成方法
java·人工智能·pytorch·python·深度学习·语言模型
扫地的小何尚1 小时前
NVIDIA RTX PC开源AI工具升级:加速LLM和扩散模型的性能革命
人工智能·python·算法·开源·nvidia·1024程序员节
wanglei2007081 小时前
生产者消费者
开发语言·python
清水白石0082 小时前
《从零到进阶:Pydantic v1 与 v2 的核心差异与零成本校验实现原理》
数据库·python
昵称已被吞噬~‘(*@﹏@*)’~2 小时前
【RL+空战】学习记录03:基于JSBSim构造简易空空导弹模型,并结合python接口调用测试
开发语言·人工智能·python·学习·深度强化学习·jsbsim·空战
2501_941877982 小时前
从配置热更新到运行时自适应的互联网工程语法演进与多语言实践随笔分享
开发语言·前端·python
酩酊仙人2 小时前
fastmcp构建mcp server和client
python·ai·mcp
且去填词3 小时前
DeepSeek API 深度解析:从流式输出、Function Calling 到构建拥有“手脚”的 AI 应用
人工智能·python·语言模型·llm·agent·deepseek
rgeshfgreh3 小时前
Python条件与循环实战指南
python
rgeshfgreh3 小时前
通达信LC1文件结构解析指南
python