【问题标题】:How to allow for multiple file names when searching through a directory in python?在python中搜索目录时如何允许多个文件名?
【发布时间】:2017-10-13 22:38:52
【问题描述】:

我怎样才能写出类似的东西:

module_path = os.path.join(root_dir,_dir,'Tests.py')

是否还能够考虑名为 Test.py 和 test.py 和 tests.py 的文件?

如果找不到文件 Tests.py,它如何检查两者中的另一个以确保编写程序的人可以看到他们的文件?

我想说的是有什么东西可以让我这样做吗?:

module_path = os.path.join(root_dir,_dir,'(T or t)est(s).py')

【问题讨论】:

    标签: python string directory operating-system sys


    【解决方案1】:

    如果您要搜索的实际上是这四个文件,那么类似以下的内容将起作用:

    import os
    
    _dir = 'test'
    names=['Test.py','test.py','Tests.py','tests.py']
    
    for fname in names:
        test_path = os.path.join(_dir, fname)
        if os.path.isfile(test_path):
            module_path = test_path
            break
    

    您需要进行修改以适应您的环境。

    【讨论】:

      【解决方案2】:

      您可以使用glob module,它支持简单 版本的正则表达式(“Unix 风格的通配符”)。例如,你可以使用这个:

      for name in glob.glob("[tT]est*.py"):
          print("I found", name) 
      

      这匹配名称​​以“Test”或“test”开始并以.py 结尾的文件。它不会按优先顺序为您提供名称,但它可能就是您所需要的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-07-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-15
        • 2019-11-17
        • 1970-01-01
        相关资源
        最近更新 更多