pythonlistfiltersubstring

how to extract files from a list using substring filter


I have a list of files from os.listdir like:

 TXSHP_20240712052921.csv
 TXSHP_20240715045301.csv
 TXSHP_FC_20210323084010.csv
 TXSHP_FC_20231116060918.csv

how do I extract only the ones where 'FC' is not in the filename

Ive tried

def get_archive_filelist_chip(archiveFldr):
    nonedi_files_chip = []
    folder = archiveFldr
    for file in os.listdir(folder):
        if  file.endswith(".csv") & 'FC' in file == False:
            nonedi_files_chip.append(file)
        else:
            pass
    #nonedi_files_chip = filter(lambda x: 'FC' not in x, nonedi_files_chip)
    return nonedi_files_chip

Solution

  • if  file.endswith(".csv") & 'FC' in file == False:
    

    Observe that bitwise AND (&) in python is more sticky than in (see Operator precedence table) so your condition is understood as

    if (file.endswith(".csv") & 'FC') in file == False:
    

    You should use boolean AND in this case and brackets (which will also help reader understand your code)

    if file.endswith(".csv") and ('FC' in file == False):
    

    though it in python not in is often used for such task, that is

    if file.endswith(".csv") and 'FC' not in file: