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


相关推荐
s1hiyu20 小时前
使用Scrapy框架构建分布式爬虫
jvm·数据库·python
2301_7634724620 小时前
使用Seaborn绘制统计图形:更美更简单
jvm·数据库·python
无垠的广袤20 小时前
【VisionFive 2 Lite 单板计算机】边缘AI视觉应用部署:缺陷检测
linux·人工智能·python·opencv·开发板
Duang007_20 小时前
【LeetCodeHot100 超详细Agent启发版本】字母异位词分组 (Group Anagrams)
开发语言·javascript·人工智能·python
浒畔居21 小时前
机器学习模型部署:将模型转化为Web API
jvm·数据库·python
抠头专注python环境配置21 小时前
基于Pytorch ResNet50 的珍稀野生动物识别系统(Python源码 + PyQt5 + 数据集)
pytorch·python
百***787521 小时前
Kimi K2.5开源模型实战指南:核心能力拆解+一步API接入(Python版,避坑全覆盖)
python·microsoft·开源
喵手21 小时前
Python爬虫实战:针对天文历法网站(以 TimeandDate 或类似的静态历法页为例),构建高精度二十四节气天文数据采集器(附xlsx导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集天文历法网站数据·构建二十四节气天文数据
zhaotiannuo_199821 小时前
Python之2.7.9-3.9.1-3.14.2共存
开发语言·python
Keep_Trying_Go21 小时前
基于GAN的文生图算法详解ControlGAN(Controllable Text-to-Image Generation)
人工智能·python·深度学习·神经网络·机器学习·生成对抗网络·文生图