【问题标题】:How to determine drive in Windows using Python?如何使用 Python 在 Windows 中确定驱动器?
【发布时间】:2021-01-09 09:28:39
【问题描述】:

我有一个名为C:/的字符串,我想检测这个字符串是否是驱动器路径。

显然,它似乎是驱动器,但我想要一个确定这是驱动器的代码或模块。

我试过os.path.isdrive,但没有这样的功能。

我认为答案很简单,但我不知道该怎么做。

我正在使用 Python 3.8 和 Window。谢谢。

【问题讨论】:

    标签: operating-system python-3.8 drive


    【解决方案1】:

    你可以使用 path.exists() 函数:

    from os import path
    path.exists("C:/")
    

    如果您只想测试驱动器的根目录(“C:/”而不是“C:/File/File2/”),您可以通过测量路径的长度来检查:

    def is_drive(path):
       if len(path) <= 3 and os.path.exists(path):
          return True
       return False
    

    如果驱动器存在,此方法将返回。我希望这会有所帮助,这实际上取决于您要使用此功能的目的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-09
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 1970-01-01
      • 2011-05-22
      相关资源
      最近更新 更多