【问题标题】:How to have all possibilities of path with specific beginning?如何拥有具有特定起点的路径的所有可能性?
【发布时间】:2021-09-23 14:52:53
【问题描述】:

我必须检查某个位置的变量文件:

variable = "40014ee0aee34570"
os.path.realpath(/dev/disk/by-id/wwn-0x{0}'.format(variable))

我需要检查是否还有40014ee0aee34570-part140014ee0aee34570-part2等。

现在我可以这样做

os.path.realpath('/dev/disk/by-id/wwn-0x{0}{1}'.format(variable, '-part1')

但是,我如何以编程方式检查此行中的每个可能性数字? 谢谢

【问题讨论】:

    标签: python path partition os.path


    【解决方案1】:

    我建议使用glob 模块。

    import glob
    
    variable = "40014ee0aee34570"
    
    # file wildcard, use * at the end to get all suffixes
    file_wildcard = "/dev/disk/by-id/wwn-0x{0}*".format(variable)
    
    possible_file_paths = glob.glob(file_wildcard)
    
    for file_path in possible_file_paths:
        os.path.realpath(file_path)
    

    【讨论】:

      【解决方案2】:

      您可以简单地将 srting 与 + 连接起来

      例子:

      string1 = "I am "
      string2 = "foo"
      string3 = string1 + string2 
      print(string3)
      
      OUT[1]:
      >> I am foo
      

      因此,您可以使用它通过所有组件(根路径、变量名、后缀、数字等)以编程方式生成文件路径:

      import os
      
      path = r"/dev/disk/by-id/"
      
      file_prefix = "wwn-0x"
      variable = "40014ee0aee34570"
      file_suffix = "-part"
      
      for number in range(0,10):
        file = os.path.join(path , file_prefix  + variable  + file_suffix + str(number))
        if os.path.exists(file):
          print(f"{file} exists")
        else :
          print(f"no file with that part number {number}")
      

      【讨论】:

      • 我做了一些更正,代码中有一些错别字
      猜你喜欢
      • 1970-01-01
      • 2018-03-20
      • 1970-01-01
      • 2019-10-22
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多