Home > Net >  For a given range of (x,y) how do I return the list of files with numbers within x, y in their name
For a given range of (x,y) how do I return the list of files with numbers within x, y in their name

Time:04-14

I have got a list of files named posture0 posture 1 posture 2 etc up to 4000. I want to use a function that takes this range and gives me the file pattern around it. The reason why I tried this I might want to get certain ranges of files (1-300),(2-219) In order to achieve this I have tried these so far:

Automate a regex search pattern.

I have found the module rgxg which does automate the pattern searching. For 0-180 it generated this result.

(180|1[0-7][0-9]|0?[0-9]{1,2})

So this was my regex.

posture (180|1[0-7][0-9]|0[0-9]{1,2}) .jpg

This didn't work because it should have gotten files like posture0 and to posture180.jpg. It got them although 0-100 was missing and also patterns like 1000 were also found with this regex.

And later on I ran this pattern on a python code.

import re

rootdir = "postures"

regex = re.compile('posture (180|1[0-7][0-9]|0[0-9]{1,2}) .jpg')

for root, dirs, files in os.walk(rootdir):
  for file in files:
    if regex.match(file):
       print(file)

It returns files but it also returns file 0-1500 and it doesn't return numbers between 0-99.

I have also searched glob but it seems I can't find such functionality on it.

Edit:Since I have had the feedback of my question being not clear.I will try to clarify it.

The Question: Is there a way to automate the search strings in regex? The one I have tried didn't work well for me since the cases I mentioned weren't captured. Thanks :)

CodePudding user response:

Here's a solution to what I think is your question. It implements a function that takes a path to a directory, a lower value and an upper value, then returns all filenames that contain the number within range defined by the lower and upper values.

import os
import re

def get_filenames_in_range(path_to_directory, lower_bound, upper_bound):
    files = []
    # Iterate through files in current directory
    for f in os.listdir(path_to_directory):
        # os.listdir captures directories as well as files
        # so filter just for files
        if os.path.isfile(f):
            # Perform a regex match for numbers
            match = re.findall(r'\d ', f)
            # If numbers are found, check whether they are within range
            if match:
                number = int(match[0])
                if number >= lower_bound and number <= upper_bound:
                    files.append(f)
    return files
  • Related