AttributeError: 'NoneType' object has no attribute 'group'

0

Can someone help me? The last row of the code gives me an error.

os.chdir("./envolventes")


diractual = os.getcwd()

ficheros = os.listdir(diractual)


lista_sin_D = [ x for x in ficheros if "D" not in x ]

import re

lista_A_menor45 = [ x for x in ficheros if int(re.match('.*?([0-9]+)$', 
x).group(1)) < 45 ]
    
asked by Alfonso 23.01.2018 в 19:37
source

2 answers

0

As the files have a .txt extension, you should change the regular expression by .*?([0-9]+).txt , thus remaining:

lista_A_menor45 = [ x for x in ficheros if int(re.match('.*?([0-9]+).txt', x).group(1)) < 45 ]

For regular expressions I highly recommend the following page to evaluate and test them: regex101

    
answered by 26.01.2018 / 08:59
source
1

You have a file that does not fit the pattern you give it.

Before extracting the group, you should check if .match() returns None . So you can apply it in a list compression you can do so:

def check(x):
    m = re.match('.*?([0-9]+)$', x)
    return False if m is None else int(m.group(1)) < 45

[ x for x in ficheros if check(x) ]

To know which files do not pass, just invert the filter:

[ x for x in ficheros if not check(x) ]
    
answered by 23.01.2018 в 19:48