python - 如何区分python中的目录和文件路径?
问题描述
我编写了以下源代码来测试 astring
是目录还是文件。
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
任何人都可以提出任何更好的技术吗?
解决方案
在 std 库中使用pathlib.Path 。
from pathlib import Path
path_string = "xxx"
pa = Path(path_string)
print(f"{pa.is_file()}")
print(f"{pa.is_dir()}")
推荐阅读
- javascript - 尝试使用 setTimeout 更新时 useState
- python - 在数组中搜索重复项
- excel - 更新/更改图表时,Application.ScreenUpdating 不起作用?
- apache-spark - Kafka 2.4 是否与 Spark 2.4 兼容?
- vbscript - VBS 文件不打印
- node.js - VS Code - 调试器不会进入函数
- string - 比较字符串的Makefile问题
- linux - 在 bash 脚本中转义大括号
- python - 我不理解的 Python 代码或 CNN 架构功能的错误
- reactjs - 反应大日历时间更改错误的偏移量