【问题标题】:How to check if a file name contains a correct amount of numbers in python?如何检查文件名是否包含python中正确数量的数字?
【发布时间】:2018-10-09 05:33:40
【问题描述】:

我正在编写一个过滤放置在特定文件夹中的文件的程序,我需要检查它们是否具有以下结构:some_name/+++/++/++++.format,其中+代表任何数字。

我的代码是这样开始的:

import glob

path = "_path_"
File_list = glob.glob(path+"/*")

for item in File_list:
  if item == path + *something*:   <-------- This is my problem
    print (True)

我将不胜感激。我正在使用 Python 3.6。

【问题讨论】:

  • 使用正则表达式将文件名与您的格式匹配docs.python.org/3/howto/regex.html
  • 你可以使用\d{3}/\d{2}/\d{4}
  • 您可以遍历文件路径字符串中的字符并计算其中出现的位数

标签: python file-read


【解决方案1】:

一些正则表达式来匹配该模式怎么样:

import re

pat = re.compile(".*\/\d{3}\/\d{2}\/\d{4}\.format")
if pat.match(item):
    # Your code here

【讨论】:

    【解决方案2】:

    您可以使用 glob 模式:

    File_list = glob.glob('/'.join((path, *('[0-9]' * n for n in (3, 2, 4)), '.format')))
    

    【讨论】:

      【解决方案3】:

      这应该会有所帮助-

      import re    
      f = 'fname/123/45/6789.txt'
      if re.match('^\w+/\d{3}/\d{2}/\d{4}', f):
          print("Correct file name format")
      

      输出:

      >> Correct file name format
      

      【讨论】:

        【解决方案4】:
        import re
        regex = r"\w+\/\d{3}\/\d{2}\/\d{4}"
        test_str = ("some_name/123/12/1234")
        matches = re.search(regex, test_str)
        if matches:
             print(True)
        else:
            print(False)
        

        使用正则表达式

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-14
          • 1970-01-01
          • 2012-06-27
          • 1970-01-01
          • 2022-11-23
          • 2016-04-19
          相关资源
          最近更新 更多