import pywikibot

pywikibot.config.family = "commons" pywikibot.config.mylang = "commons"

category_to_add = 'Category:Members of the 1st Congress of Deputies' mypages = ['Category:Marta Mata'] for mypage in mypages: current_category = pywikibot.Category(pywikibot.Site('commons'), mypage) current_category_memberships = list(current_category.categories()) for current_category_membership in current_category_memberships: print(current_category_membership.text)

for mypage in mypages:
    category = pywikibot.Category(pywikibot.Site('commons'), mypage)
    subcategories = list(category.categories())
    print(subcategories)
    for subcategory in subcategories:
        if category_to_add == subcategory.text:
            print('already existing')
        else:
            print('not matched in '+subcategory.text)