QuickSnip LogoA light blue logo with a thunderbolt in bracketsQuickSnip

Find files

Find all the files in a directory using a predicate function.

  • filesystem
  • file_search
  • c++17
  • os
  • file
  • search

Code

import os

def find_files(directory, file_type):
  file_type = file_type.lower()  # Convert file_type to lowercase
  found_files = []

  for root, _, files in os.walk(directory):
    for file in files:
      file_ext = os.path.splitext(file)[1].lower()
      if file_ext == file_type:
        full_path = os.path.join(root, file)
        found_files.append(full_path)

  return found_files

# Example Usage:
find_files('/path/to/your/directory', '.pdf') # Returns all .pdf in directory

Usage

// Find all files with size greater than 10MB
auto files = find_files("Path", [](const auto& p) {
    return std::filesystem::file_size(p) > 10 * 1024 * 1024;
});

// Find all files with ".pdf" as extension
auto files = find_files("Path", [](const auto& p) {
    return p.extension() == ".pdf";
});

// Find all files writed after The New Year
#include <chrono>
// need std=c++20
auto jan_1_2025 = std::filesystem::file_time_type::clock::from_sys(
    std::chrono::sys_days{std::chrono::year{2025}/std::chrono::month{1}/std::chrono::day{1}}
);
auto files = find_files("Path", [jan_1_2025](const auto& p) {
    return std::filesystem::last_write_time(p) > jan_1_2025;
}),