Home > Software design >  Find all files starting with given path and name
Find all files starting with given path and name

Time:08-05

I am finding lots of examples for how to list files in a directory, but not to many on how to find files given part of the path.

I have this string

/home/myuser/folder/Files/2020-08-04_1934_split_

I would like to use this to find all files starting with that path and name. So it should find files such as:

/home/myuser/folder/Files/2020-08-04_1934_split_001.mp4
/home/myuser/folder/Files/2020-08-04_1934_split_002.mp4
...

Do I need to parse the string, extract the directory and use os.listdir to iterate over all files and check them one by one, or is there a simpler way?

This is the code I came up with to solve the problem.

def GetAllFilesStartingWith(self, filePathStart):
    filesDirectory = os.path.dirname(filePathStart)
    fileStart = Path(filePathStart).name

    resultFiles = []
    
    for file in os.listdir(filesDirectory):
        if file.startswith(fileStart):
            completePath = os.path.join(filesDirectory, file)
            resultFiles.append(completePath)

    return resultFiles

CodePudding user response:

Maybe something along these lines would work?

import glob

path = "/home/myuser/folder/Files/2020-08-04_1934_split_"
result_files = glob.glob(path   "**/*.*")

CodePudding user response:

Unix systems has grep command, maybe powershell has something too. So you can use native file-search engine instead of a slower python version. Sure you can modify this command as you want

import os
file_starts_with = "2022"
os.system(f'ls -1 | grep "^{file_starts_with}"')

Or you can use smth like

ls -1 | grep "^2020" >> files.txt

in your terminal

This saves the files names into the files.txt

  • Related