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


相关推荐
笨笨聊运维1 天前
CentOS官方不维护版本,配置python升级方法,无损版
linux·python·centos
Gerardisite1 天前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
小毛驴8501 天前
软件设计模式-装饰器模式
python·设计模式·装饰器模式
闲人编程1 天前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
weixin_457760001 天前
Python 数据结构
数据结构·windows·python
合作小小程序员小小店1 天前
web网页,在线%抖音,舆情,线性回归%分析系统demo,基于python+web+echart+nlp+线性回归,训练,数据库mysql
python·自然语言处理·回归·nlp·线性回归
q***2511 天前
Python中的简单爬虫
爬虫·python·信息可视化
最晚的py1 天前
Python Matplotlib
python·数据分析