Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #177 Find files for a list of filename extensions

Construct a list L that contains all filenames that have the extension ".jpg" , ".jpeg" or ".png" in directory D and all its subdirectories.

import 'dart:io';
import 'package:path/path.dart' as p;
var extensions = [".jpg", "jpeg", ".png"];
var L = Directory(D)
    .listSync(recursive: true)
    .where((file) => extensions.contains(p.extension(file.path)))
    .toList();
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
string D = @"C:\The\Search\Path";

// Assumes that the file system is case insensitive
HashSet<string> exts = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase) { "jpg", "jpeg", "png" };
IEnumerable<string> L =
Directory
    .EnumerateFiles(D, "*", SearchOption.AllDirectories)
    .Where(currentFile => exts.Contains(Path.GetExtension(currentFile)));
import std.algorithm;
import std.conv;
import std.file;
immutable exts = ["jpg", "jpeg", "png"];
auto L = D.dirEntries(SpanMode.depth)
          .map!(to!string)
          .filter!(f => exts.canFind(f.split(".")[$-1]));
import "path/filepath"
import "strings"
L := []string{}
err := filepath.Walk(D, func(path string, info os.FileInfo, err error) error {
	if err != nil {
		fmt.Printf("failure accessing a path %q: %v\n", path, err)
		return err
	}
	for _, ext := range []string{".jpg", ".jpeg", ".png"} {
		if strings.HasSuffix(path, ext) {
			L = append(L, path)
			break
		}
	}
	return nil
})
import static java.util.Arrays.asList;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
static List<String> L = new ArrayList<>();
record Find(File d, String ... t) {
    Find { get(d, t); }
    void get(File d, String ... t) {
        File a[] = d.listFiles();
        if (a == null) return;
        for (File f : a)
            if (f.isDirectory()) get(f, t);
            else asList(t).forEach(s -> {
                if (f.getName().endsWith(s))
                    L.add(f.getName());
            });
    }
}
uses FileUtil;
L := FindAllFiles(D, '*.jpg;*.jpeg;*.png', True);
use File::Find;
my @L;
find(sub {
  push @L, $File::Find::name
     if /(.jpg|.jpeg|.png)$/;
}, $D);


import os
extensions = [".jpg", ".jpeg", ".png"]
L = [f for f in os.listdir(D) if os.path.splitext(f)[1] in extensions]
import re
import os
filtered_files = ["{}/{}".format(dirpath, filename) for dirpath, _, filenames in os.walk(D) for filename in filenames if re.match(r'^.*\.(?:jpg|jpeg|png)$', filename)]
import glob
import itertools
list(itertools.chain(*(glob.glob("*/**.%s" % ext) for ext in ["jpg", "jpeg", "png"])))
import glob
import os
extensions = [".jpg", ".jpeg", ".png"]
L = [f for f in glob.glob(os.path.join(D, "**/*"), recursive=True) if os.path.splitext(f)[1] in extensions]
L = Dir.glob(File.join("**", "*.{jpg,jpeg,png}"), base: D)
use std::path::{Path, PathBuf};
let d = Path::new("/path/to/D");
let l: Vec<PathBuf> = d
    .read_dir()?
    .filter_map(|f| f.ok())
    .filter(|f| match f.path().extension() {
        None => false,
        Some(ex) => ex == "jpg" || ex == "jpeg" || ex == "png"
    })
    .map(|f| f.path())
    .collect();

New implementation...
< >
Bart