【问题标题】:In Python, How do I check whether a file exists starting or ending with a substring?在 Python 中,如何检查是否存在以子字符串开头或结尾的文件?
【发布时间】:2017-11-12 03:15:53
【问题描述】:

我知道os.path.isfile(fname),但现在我需要搜索是否存在名为FILEnTEST.txt 的文件,其中n 可以是任何正整数(因此可以是FILE1TEST.txtFILE9876TEST.txt

我想这个问题的解决方案可能涉及文件名以 OR 开头/结尾的子字符串,其中涉及以某种方式调用 os.path.isfile('FILE' + n + 'TEST.txt') 并将 n 替换为任意数字,但我不知道如何处理这两种解决方案。

【问题讨论】:

    标签: python file filesystems substring


    【解决方案1】:

    你也可以这样做:

    import os
    import re
    
    if len([file for file in os.listdir(directory) if re.search('regex', file)]):
        # there's at least 1 such file
    

    【讨论】:

      【解决方案2】:

      您需要编写自己的过滤系统,获取目录中的所有文件,然后将它们匹配到正则表达式字符串并查看它们是否通过测试:

      import re
      
      pattern = re.compile("FILE\d+TEST.txt")
      dir = "/test/"
      for filepath in os.listdir(dir):
          if pattern.match(filepath):
              #do stuff with matching file
      

      我没有靠近安装了 Python 来测试代码的机器,但它应该是类似的东西。

      【讨论】:

        【解决方案3】:

        你可以使用正则表达式:

        /FILE\d+TEST.txt/
        

        例如:regexr.com

        然后您可以使用上述正则表达式并遍历目录中的所有文件。

        import re
        import os
        
        filename_re = 'FILE\d+TEST.txt'
        for filename in os.listdir(directory):
            if re.search(filename_re, filename):
                # this file has the form FILEnTEST.txt
                # do what you want with it now
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-11-22
          • 1970-01-01
          • 2012-03-22
          • 1970-01-01
          • 2012-12-31
          • 2012-02-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多