How to search in path, but omit folders – python


I want to search XML files in folder:

path = 'C:/Users/STJ2TW/Desktop/TDD/TD/cell02/td/cell'

In this folder there are XML files and also two folders: supplemenet and serialno

I want to find only XML files and omit these folders, so I’m doing code:

path = 'C:/Users/STJ2TW/Desktop/TDD/TD/cell02/td/cell'
for filename in os.listdir(path):
    if '.' not in filename:
        if 'MASTER' not in filename:
            if 'GHOST' and 'serialno' and 'supplement' not in filename: 
                fullname = os.path.join(path, filename)

But there is an error:

PermissionError                           Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_14576/ in <module>
    109             if 'GHOST' and 'serialno' and 'supplement' not in filename:
    110                 fullname = os.path.join(path, filename)
--> 111                 PN, GH, GH_Design_standard = get_data_from_xml(fullname)
    113                 PN_list.append(PN)

~\AppData\Local\Temp/ipykernel_14576/ in get_data_from_xml(path)
---> 23     tree = ET.parse(path)
     24     #tree = etree.XML(path)
     25     root = tree.getroot()

C:\Program Files\Anaconda3\lib\xml\etree\ in parse(source, parser)
   1227     """
   1228     tree = ElementTree()
-> 1229     tree.parse(source, parser)
   1230     return tree

C:\Program Files\Anaconda3\lib\xml\etree\ in parse(self, source, parser)
    567         close_source = False
    568         if not hasattr(source, "read"):
--> 569             source = open(source, "rb")
    570             close_source = True
    571         try:

PermissionError: [Errno 13] Permission denied: 'C:/Users/STJ2TW/Desktop/TDD/TD/cell02/td/cell\\serialno'

I wonder how can I repair this. Thanks in advance for any help.

>Solution :

I think your problem is actually this line:

if 'GHOST' and 'serialno' and 'supplement' not in filename: 

Which does not work as you’d expect. I think what you need is something like:

# your code...
    excl_list = ['GHOST', 'serialno', 'supplement']
    if all([element not in filename for element in excl_list]):
# your code...

Leave a ReplyCancel reply