Skip to content
The Chat Archive
gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)

PYTHON find files under path

  1. User

    PYTHON find files under path

  2. Assistant

    To find files under a path using Python, you can use the os module. Here's an example code snippet:

    import os
    
    path = 'path/to/directory'
    
    files = []
    
    for r, d, f in os.walk(path):
        for file in f:
            if '.txt' in file:  # Change the extension as needed
                files.append(os.path.join(r, file))
                
    print(files)
    

    In this code, the os.walk() function recursively goes through all the directories and sub-directories under the given path. The function returns three values - the root folder, the directories, and the files in that folder.

    We use a for loop to iterate over the files in each folder. The if statement checks if the file has the desired extension (change '.txt' to whatever file extension you want to search for), and then appends the file path to a list of files.

    Finally, the code prints out the list of file paths. You can use this list to further manipulate or process the files as needed.