Home > OS >  run function after filename
run function after filename

Time:03-23

I want to run different functions depending on the filename

This is my code:

    entries = Path(infile)
    for file in sorted(entries.glob("*.TXT")): 
        if file == '*Blk.TXT':
            outlier.outlier_Cu_blk(file)
        elif file == '*s0*.TXT':
            outlier.outlier_Cu_std(file)
        else:
            outlier.outlier_Cu_sample(file)

But it is just calling "else", even with the files containing "Blk.TXT" and "s0". What am I doing wrong?

CodePudding user response:

The '==' didn't use regex like matching, you should use re for this purpose:


import re
blk_txt_rgx = re.compile(r'.*Blk\.TXT')
s0_txt_rgx = re.compile(r'.*s0.*\.TXT')

entries = Path(infile)
for file in sorted(entries.glob("*.TXT")): 
    if blk_txt_rgx.match(file):
        outlier.outlier_Cu_blk(file)
    elif s0_txt_rgx.match(file):
        outlier.outlier_Cu_std(file)
    else:
        outlier.outlier_Cu_sample(file)

CodePudding user response:

== doesn't take in * as separators, if you want to do this further, you need to consider using regex.

entries = Path(infile)
for file in sorted(entries.glob("*.TXT")): 
    file = str(file)
    if file.endswith('Blk.TXT'):
        outlier.outlier_Cu_blk(file)
    elif file.endswith('.TXT') and 's0' in file:
        outlier.outlier_Cu_std(file)
    else:
        outlier.outlier_Cu_sample(file)

CodePudding user response:

Python does not support wildcards like * in a normal string. can use a regex to do this. A wildcard character that can represent one arbitrary char is the dot (.). To repeat this multiple times we can add a *. make sure to add a backslash (\) to escape the dot in your filename.

import re
blk_regex = re.compile(r'.*Blk\.TXT')
slk_regex = re.compile(r'.*s0.*\.TXT')

for file in sorted(entries.glob("*.TXT")): 
if blk_regex.match(file):
    outlier.outlier_Cu_blk(file)
elif slk_regex.match(file):
    outlier.outlier_Cu_std(file)
else:
    outlier.outlier_Cu_sample(file)
  • Related