Home > Mobile >  Loop Directory (folder and Subfolder in Python app)
Loop Directory (folder and Subfolder in Python app)

Time:01-16

I am trying to have an app that loops through a directory (folder and sub) searching for multiple extensions or keywords and outputs the list in a dynamic frame but the code (or returns Zero if nothing found).

Current code fails both when multiple extensions (or keywords) are inputted or fails by grouping multiple results in a single row of the frame.

I need help in debugging my code posted below.

Thank you

   from st_aggrid import AgGrid
    import streamlit as st
    import pandas as pd
    import os

    office= st.text_input("Enter your Office : ")
    path= st.text_input("Enter directory path to search : ")
    extensions= st.text_input("Enter the File Extension :")

    file_names = [fn for fn in os.listdir(path) if any(fn.endswith(ext) for ext in extensions)]
    df = pd.DataFrame({'Office' : [office],'Directory' : [path],'File_Name' : file_names})
    AgGrid(df, fit_columns_on_grid_load=True)

CodePudding user response:

There are some problems in your code:

  1. When getting the extension using st.text_input the returned value is a string not a list of extension. In order to solve this just ask the user to enter the extension seperated with a comma and split the string to get a list of extensions.

    extensions= st.text_input("Enter the File Extension (Seperated with comma):").split(",")
    
  2. when you first run the Streamlit code the values of office, path, extensions are None causing a FileNotFoundError so we need to run the code to loop through a directory and display files only if the these values are not None.

     if office and path and extensions:
         # code
    
  3. Searching file is not recursive so we need to change it to get subfolder files also we can do this using the solution suggested in this question Structure

    These are examples of the output of the working code:

    out1

    out2

  •  Tags:  
  • Related