Search code examples
python-3.xpython-os

Iterate through folders to open files of a specific type


For a script I am looking in a directory and I want to open all .ifc files in the directory, including all subfolders. To do this I am using the os package.

The point I am stuck is is to create the correct paths of the subfolders I require to open. Including subdir in the os.path.join does not give the desired result as then the main folder is skipped. How do I go about creating the correct paths?

I have included a MWE of the directory and a MWE of the code I am currently implementing.

MWE of directories I want to open:

  • C:\This folder\This file.ifc
  • C:\This folder\Not this file.docx
  • C:\This folder\Also this folder\But not this file.xlsx
  • C:\This folder\Also this foldder\And also this file.ifc

MWE:

import os
import tinker as tk
from tkinter import filedialog

#Select directory
root = tk.Tk()
root.withdraw()
directory = filedialog.askdirectory()

for root,subdir,files in os.walk(directory):
    #Select only .ifc files
    for filename in files:
        if filename.endswith(".ifc"):
            #Construct full filepath for open
            ifc_filepath = os.path.join(root,filename)

            #Open the .ifc file
            ifc_file = open(ifc_filepath)
         else:
            continue


Solution

  • Why you don't use glob?

    from pathlib import Path
    from os.path import join
    
    
    base_dir = './test'
    file_extension = 'xml'
    
    for file_path in Path(base_dir).glob(f'**/*.{file_extension}'):
        file_path = join(base_dir, file_path)
        print(file_path) # do whatever you need with these files