from xml.etree import ElementTree as ET import shutil, os text = """ Microsoft Excel0falseWorksheets10Named Ranges4typesemptyscattermerged_cellssheet_not_to_readssd_error1ssd_error2ssd_error3semistrucdata1semistrucdata2single_nrtable1table2table3falsefalsefalse16.0300""" os.makedirs('subdir1') os.makedirs('subdir2') with open('subdir1/app.xml', 'w') as file: original_text = file.write(text) with open('subdir2/app.xml', 'w') as file: original_text = file.write(text) # correctly closed filehandle from source = io file handle namespace = [] with open('subdir1/app.xml', 'r') as file: for event, elem in ET.iterparse(source=file, events=("start", "start-ns", "end-ns")): if event == "start-ns": elem = ('default', elem[1]) if elem[0] == '' else elem namespace.append(elem) if event == "start": break print(namespace) shutil.rmtree('subdir1') # incorrectly closed filehandle from source = string type namespace = [] for event, elem in ET.iterparse(source='subdir2/app.xml', events=("start", "start-ns", "end-ns")): if event == "start-ns": elem = ('default', elem[1]) if elem[0] == '' else elem namespace.append(elem) if event == "start": # ISSUE IS HERE: the break which seems okay to code in a for-loop actually breaks out of a while True loop within iterparse # that ends up not closing the file, thereby keeping a lock on the file. # this is demonstrated below when we try to delete the folder containing this file, but we cannot do so. break print(namespace) shutil.rmtree('subdir2')