【问题标题】:How can I differentiate between a directory and a file path in python?如何区分python中的目录和文件路径?
【发布时间】:2021-07-18 02:59:07
【问题描述】:

我编写了以下源代码来测试string是目录还是文件。

import platform
from PathValidation import PathValidation # https://stackoverflow.com/a/34102855/159072


class SystemUtils:
    @staticmethod
    def is_file(path_string: str) -> bool:
        return not SystemUtils.is_directory(path_string)        ​
   ​
    ​@staticmethod
​    def is_directory(path_string: str) -> bool:
​       is_win_os = SystemUtils.is_windows()
​           
    ​    if is_win_os is True:
       ​     path_string = SystemUtils.to_windows_path(path_string)
    ​    else:
            ​path_string = SystemUtils.to_unix_path(path_string)
    ​
    ​    valid = PathValidation.is_pathname_valid(path_string)
    ​
    ​    if valid is False:
           ​return False
    ​
    ​    if is_win_os is True:
       ​     if path_string.startswith("\\") or path_string.endswith("\\"):
           ​     return True
    ​    else:
       ​     if path_string.startswith("/") or path_string.endswith("/"):
           ​     return True
    ​    # END of outer if
    ​    return False

   ​ @staticmethod
   ​ def to_windows_path(path_string) -> str:
       ​ path_string = path_string.replace("/", "\\")
        ​return path_string

   ​ @staticmethod
   ​ def to_unix_path(path_string) -> str:
        ​path_string = path_string.replace("\\", "/")
        ​return path_string

   ​ @staticmethod
   ​ def is_windows() -> bool:
       ​ system_type = platform.system()
       ​ if system_type == "Windows":
            ​return True
        ​else:
            ​return False

   ​ @staticmethod
   ​ def is_linux() -> bool:
        ​system_type = platform.system()
        ​if system_type == "Linux":
           ​ return True
       ​ else:
           ​ return False

    ​@staticmethod
    ​def is_darwin() -> bool:
        ​system_type = platform.system()
       ​ if system_type == "Darwin":
            ​return True
       ​ else:
           ​ return False

谁能推荐更好的技术?

【问题讨论】:

  • 你检查过os.pathpathlibglob这些是像Django这样的框架使用的库。在pathlib你有pathlib.is_dir()pathlib.PureWindowsPath()等方法。

标签: python directory


【解决方案1】:

在标准库中使用pathlib.Path

from pathlib import Path

path_string = "xxx"

pa = Path(path_string)

print(f"{pa.is_file()}")
print(f"{pa.is_dir()}")

【讨论】:

    猜你喜欢
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 2011-09-01
    • 1970-01-01
    • 2010-09-17
    • 1970-01-01
    相关资源
    最近更新 更多