Python 小技巧:路径标准化函数

开发目的

在实际工作中,笔者经常遇到特殊的文件夹路径或者文件路径,由于缺乏经验需要在此浪费较多时间。进而想要写一个路径标准化函数,用 pathlib 包替换 os 包,把输入路径转成标准的可读格式,即输入可能是带有双引号的路径或者路径间隔是“\”、“\”、“/” 等转成标准格式。

原代码

    def normalize_path(path):
        path = re.sub(r'^["\']|["\']$', '', path.strip())
        path = path.replace('/', '\\')
        path = path.replace('\\\\', '\\')
        return path

优化过程

1.0

  • 使用pathlib内置方法,这些方法通常是用C实现的,效率高
  • 优先考虑了绝对路径和相对路径、内存和避免Path的报错
from pathlib import Path
import os

def normalize_path(path_input: str) -> Path:
    """
    Convert input path string to standardized Path object.
    Handles quotes, different separators, and resolves relative paths.
    """
    # Remove quotes and extra whitespace
    clean_path = path_input.strip().strip('"').strip("'")
    
    # Convert to Path object and resolve to absolute path
    try:
        path = Path(clean_path).resolve()
        return path
    except (OSError, ValueError):
        # Return unresolved path if resolution fails
        return Path(clean_path)

2.0

  • 使用pathlib.Path自动处理不同操作系统的路径分隔符
  • 优化去除字符串两端的引号和空格
  • 当路径可解析时,使用resolve()方法解析相对路径和符号链接,返回最准确的解析结果
  • 当路径不可解析时,提供合理的回退方案,回退到使用absolute()方法
import os
import logging
from pathlib import Path
from typing import Union

def normalize_path(input_path: Union[str, Path]) -> Path:
    """
    标准化路径函数
    
    将带有各种引号、不同分隔符的路径转换为标准的Path对象
    处理以下情况:
    - 去除双引号、单引号
    - 统一处理"\\"、"/"和"\"分隔符
    - 解析相对路径和特殊符号(如".", "..")
    
    参数:
        input_path: 输入的路径字符串或Path对象
        
    返回:
        标准化的Path对象
    """
    # 如果已经是Path对象,直接返回
    if isinstance(input_path, Path):
        return input_path.resolve()
    if not isinstance(input_path, (str, Path)):
    	raise TypeError(f"输入路径必须是字符串或Path对象,收到 {type(input_path)}")
    	
    # 移除字符串两端的引号和空格
    path_str = str(input_path).strip(' \t\n"\'')
    # 使用Path创建路径对象,pathlib会自动处理不同平台的分隔符
    path_obj = Path(path_str)
    
    # 解析路径(解决相对路径、符号链接等)
	try:
	    return path_obj.resolve()
    except (OSError, PermissionError, FileNotFoundError) as e:
    	# 记录错误日志
        logging.warning(f"文件系统错误: {e}, 使用绝对路径作为回退方案")
        return path_obj.absolute() # 返回绝对路径作为回退方案
	except Exception as e:
	    logging.warning(f"路径解析失败: {e}, 使用绝对路径作为回退方案")
	    return path_obj.absolute() # 返回绝对路径作为回退方案
import os
import logging
from pathlib import Path
from typing import Union

def normalize_path(input_path: Union[str, Path]) -> Path:
    """
    Path normalization function.
    
    Converts paths with various quotes and different separators to a standardized Path object.
    Handles the following cases:
    - Removal of double quotes, single quotes
    - Uniform handling of "\\", "/", and "\" separators
    - Resolution of relative paths and special symbols (e.g., ".", "..")
    
    Parameters:
        input_path: Input path string or Path object.
        
    Returns:
        Normalized Path object.
    """
    
    # Type validation
    if not isinstance(input_path, (str, Path)):
        raise TypeError(f"Input path must be a string or Path object, received {type(input_path)}")
    
    # Return directly if already a Path object
    if isinstance(input_path, Path):
        return input_path.resolve()

    # Remove quotes and whitespace from both ends of the string
    path_str = str(input_path).strip(' \t\n"\'')
    
    # Create a Path object - pathlib automatically handles platform-specific separators
    path_obj = Path(path_str)
    
    # Resolve path (handles relative paths, symbolic links, etc.)
    try:
        return path_obj.resolve()
    except (OSError, PermissionError, FileNotFoundError) as e:
        # Log error
        logging.warning(f"Filesystem error: {e}, proceeding with absolute path as fallback")
        return path_obj.absolute() # Return absolute path as fallback solution
    except Exception as e:
        # Log error
        logging.warning(f"Unknown error encountered during path resolution: {e}, returning absolute path")
        return path_obj.absolute() # Return absolute path as fallback solution
使用Windows远程桌面连接树莓派的详细教程如下: ### 安装相关服务 1. 删除原树莓派系统自带的xrdp(基于vnc)和tightvnc: ```bash sudo apt-get purge tightvnc xrdp ``` 2. 重新在树莓派系统安装的xrdp和tightvnc: ```bash sudo apt-get install tightvncserver xrdp ``` 若出现错误请执行: ```bash sudo apt update && sudo apt upgrade ``` 也可按如下步骤操作: 1. 安装tightvncserver,tightvncserver为xrdp提供基础服务: ```bash sudo apt-get install tightvncserver ``` 2. 安装xrdp,xrdp是一个开源的远程桌面服务器: ```bash sudo apt-get install xrdp ``` 3. 如果开着防火墙ufw ,那么打开服务器上的远程桌面访问端口(树莓派防火墙默认是关闭的): ```bash sudo ufw allow 3389 ``` 4. 重启两个服务: ```bash sudo service ufw restart sudo service xrdp restart ``` ### 查看树莓派地址 此步骤在引用中未详细说明查看方法,可通过树莓派连接的路由器管理界面或使用命令行工具(如`ifconfig` )查看树莓派的IP地址。 ### 利用电脑远程桌面连接树莓派 1. 在windows上按下win + r打开运行窗口并输入:“mstsc”,打开远程桌面,输入获取到的树莓派地址,点击“连接”。 2. 弹出窗口,点击“是” ,然后出现远程桌面用户登录界面,输入树莓派账号密码(账号:pi 密码为:raspberry) ,回车或者点击“OK”进入树莓派桌面。 3. 在弹出的连接界面上选择Xorg协议,然后输入树莓派的用户名和密码后点击确定。 ### 可能遇到的问题及解决办法 1. 半天连不上树莓派,原因可能是树莓派上的3389端口没打开,需执行`sudo ufw allow 3389`打开端口。 2. 输入正确的用户名和密码 ,显示错误关键字:xrdp problem connecting,是因为tightvncserver没有安装,或者安装顺序不对。切记先安装tightvncserver,再安装xrdp。如果顺序反了,建议直接重启树莓派 [^2][^5]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值