简体   繁体   中英

Python compare filename with folder name

I just start python and i have to compare filename with folder name to launch the good sh script. (i'm using airflow)

import glob
import os
import shutil
from os import path

odsPath = '/apps/data/02_ODS/'
receiptPath = '/apps/data/80_DATA/01_Receipt/'


for files in os.listdir(receiptPath):
    if(files.startswith('MEM_ZMII') or files.startswith('FMS') and files.endswith('.csv')):
        parsedFiles = files.split('_')
        pattern = '_'.join(parsedFiles[0:2])
        fileName = '_'.join(parsedFiles[2:5])
        fileName = fileName.split('-')[0].lower()
        # print('appCode: ', pattern)
        # print('fileName: ', fileName)


for odsFolder in os.listdir(odsPath):
    if(odsFolder == fileName):
        print('it exist: ', str(fileName))
    else:
        print('it\'s not')

I got 3 files in receiptPath , it only matching for 1 file, but not the others. Can someone help me?

Thank a lot!

Ok, your problem is that you overwrite your variable fileName , so at the end of the first for loop, it only keeps the last value, which is material_makt . The solution consists in saving all the filenames in a list fileNames_list , and then you can check if (odsFolder in fileNames_list) :

import glob
import os
import shutil
from os import path

odsPath = '/apps/data/02_ODS/'
receiptPath = '/apps/data/80_DATA/01_Receipt/'


fileNames_list = []
for files in os.listdir(receiptPath):
    if(files.startswith('MEM_ZMII') or files.startswith('FMS') and files.endswith('.csv')):
        parsedFiles = files.split('_')
        pattern = '_'.join(parsedFiles[0:2])
        fileName = '_'.join(parsedFiles[2:5])
        fileName = fileName.split('-')[0].lower()
        fileNames_list.append(fileName)

for odsFolder in os.listdir(odsPath):
    if (odsFolder in fileNames_list):
        print('it exist:', str(odsFolder))
    else:
        print('it\'s not')

Output :

it exist: zcormm_familymc
it exist: kpi_obj_data
it exist: material_makt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM