Slowflake
Slowflake

Reputation: 91

How to check if a file name contains a correct amount of numbers in python?

I am writing a program which filters files placed in a specific folder and I need to check whether they have this structure: some_name/+++/++/++++.format, where + represents any digit.

Here is how my code starts:

import glob

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

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

I would appreciate any help. I am working with Python 3.6.

Upvotes: 1

Views: 2514

Answers (4)

Naren P
Naren P

Reputation: 214

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)

Use Regex

Upvotes: 1

jar
jar

Reputation: 2908

This should help-

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

Output:

>> Correct file name format

Upvotes: 1

blhsing
blhsing

Reputation: 106658

You can use glob pattern:

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

Upvotes: 2

Sven Harris
Sven Harris

Reputation: 2939

How about some regex to match that pattern:

import re

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

Upvotes: 3

Related Questions