0

I have written the following source code to test whether a string is a directory or a file.

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

Can anyone suggest any better technique?

user366312
  • 16,949
  • 65
  • 235
  • 452
  • Have you checked [os.path](https://docs.python.org/3/library/os.path.html), [pathlib](https://docs.python.org/3/library/pathlib.html) and [glob](https://docs.python.org/3/library/glob.html) these are the libraries that frameworks like Django uses. In `pathlib`you have methods like `pathlib.is_dir()`, `pathlib.PureWindowsPath()`, etc. – emichester Apr 23 '21 at 23:27

1 Answers1

0

use pathlib.Path, in the std library.

from pathlib import Path

path_string = "xxx"

pa = Path(path_string)

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

JL Peyret
  • 10,917
  • 2
  • 54
  • 73