Skip to main content
 首页 » 编程设计

python-3.x之确定路径在类构造函数中是否有效

2025年01月19日14mate10pro

在不违反 constructor should do work 的准则的情况下,我需要确定提供的字符串 (destination_directory) 在构造函数中分配之前是否是有效路径。

它不一定存在,但提供的字符串必须是有效的,即没有无效符号或非法字符。我的项目只能在 Windows 上运行,不能在 Linux 上运行。

我看了this页面,但答案似乎尝试打开目录以测试提供的字符串是否有效。

我也试过 os.path.isabs(path) 但它没有提供我需要的结果。例如,它表示 T:\\\\Pictures 是绝对路径,虽然这可能是正确的,但 \\\\ 应该表示该路径无效。

是否有一种简洁的、也许是单行的方式来实现我想要的?

def __init__(self, destination_directory: str) 
    self._validate_path(path=destination_directory) 
    self.destination_directory = destination_directory 
 
def _validate_path(self, path) 
    # code to validate path should go here. 

请您参考如下方法:

我们现在讲一些关于路径的事情,它至少包含一个盘符和子目录。

我们也有关于 what symbols are not 的规则目录中允许。我们还知道驱动器号包含单个字符。

我们不允许我们类的用户传递完整路径,而是将其分解,只允许目录名称的有效字符串和驱动器的一个字母。当一切都通过验证后,我们可以使用 os 模块来构建我们的路径。

下面是我将如何构建我的 Folder 类:

class Folder: 
 
    def __init__(self, *subdirectories, root_drive): 
        self._validate_drive_letter(letter = root_drive) 
        self._validate_path(path=subdirectories) 
 
        self._root_drive = root_drive 
        self._subdirectories = subdirectories 
 
    def _validate_drive_letter(self, letter): 
        if not letter or len(letter) > 2 or not letter.isalpha(): 
            raise ValueError("Drive letter is invalid") 
 
    def _validate_path(self, path): 
        self._forbidden_characters = ["<", ">", ":", "/", '"', "|", "?", "*", '\\'] 
        for character in path: 
            for item in character: 
                if item in self._forbidden_characters: 
                    raise ValueError("Directory cannot contain invalid characters") 
 
    def construct_full_path(self) -> str: 
        # use the os module and constructor parameters to build a valid path 
 
    def __str__(self) -> str: 
        return f"Drive Letter: {self._root_drive} Subdirectories: {self._subdirectories}" 

主要:

def main(): 
 
    try: 
 
        portable_drive = Folder("Pictures", "Landscape", root_drive="R") # Valid 
        # Using the construct_full_path() function, the returned string would be: 
        # R:\Pictures\Landscape 
        # Notice the user doesn't provide the : or the \, the class will do it. 
 
        vacation_pictures = Folder("Vac??tion", root_drive="T") # Will raise ValueError 
        # If we fix the error and call construct_full_path() we will get T:\Vacation  
 
    except ValueError as error: 
        print(error) 
    else: 
        print(portable_drive) 
        print(vacation_pictures) 
 
 
if __name__ == "__main__": 
    main() 

这可能不是最好的方法,但它确实有效。我知道嵌套的 for 循环不好,但我没有看到任何其他方法来验证 string 的单个字符。