How to get list of files with a specific extension in a given folder?
#define BOOST_FILESYSTEM_VERSION 3
#define BOOST_FILESYSTEM_NO_DEPRECATED
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem;
/**
* \brief Return the filenames of all files that have the specified extension
* in the specified directory and all subdirectories.
*/
std::vector<fs::path> get_all(fs::path const & root, std::string const & ext)
{
std::vector<fs::path> paths;
if (fs::exists(root) && fs::is_directory(root))
{
for (auto const & entry : fs::recursive_directory_iterator(root))
{
if (fs::is_regular_file(entry) && entry.path().extension() == ext)
paths.emplace_back(entry.path().filename());
}
}
return paths;
}
Find all files in a directory with extension .txt in Python
You can use glob
:
import glob, os
os.chdir("/mydir")
for file in glob.glob("*.txt"):
print(file)
or simply os.listdir
:
import os
for file in os.listdir("/mydir"):
if file.endswith(".txt"):
print(os.path.join("/mydir", file))
or if you want to traverse directory, use os.walk
:
import os
for root, dirs, files in os.walk("/mydir"):
for file in files:
if file.endswith(".txt"):
print(os.path.join(root, file))
Find a file with a certain extension in folder
Look at the System.IO.Directory
class and the static method GetFiles
. It has an overload that accepts a path and a search pattern. Example:
string[] files = System.IO.Directory.GetFiles(path, "*.txt");
List all files in a directory with a certain extension
I suggest you to firstly search the files and then perform the ls -l
(or whatever else). For example like this:
find . -name "*php" -type f -exec ls -l {} \;
and then you can pipe the awk
expression to make the addition.
List files with certain extensions with ls and grep
Why not:
ls *.{mp3,exe,mp4}
I'm not sure where I learned it - but I've been using this.
How to retrieve recursively any files with a specific extensions in PowerShell?
If sorting by Length is not a necessity, you can use the -Name
parameter to have Get-ChildItem
return just the name, then use [System.IO.Path]::GetFileNameWithoutExtension()
to remove the path and extension:
Get-ChildItem -Path .\ -Filter *.js -Recurse -File -Name| ForEach-Object {
[System.IO.Path]::GetFileNameWithoutExtension($_)
}
If sorting by length is desired, drop the -Name
parameter and output the BaseName
property of each FileInfo
object. You can pipe the output (in both examples) to clip
, to copy it into the clipboard:
Get-ChildItem -Path .\ -Filter *.js -Recurse -File| Sort-Object Length -Descending | ForEach-Object {
$_.BaseName
} | clip
If you want the full path, but without the extension, substitute $_.BaseName
with:
$_.FullName.Remove($_.FullName.Length - $_.Extension.Length)
Get all files with a specific extension
Just add an if
statement:
@echo off
for %%f in (*.ext) do (
if "%%~xf"==".ext" echo %%f
)
Get only file with given extension in directory
I would recommend using Get-ChildItem
's -include
parameter:
Get-ChildItem $dir -include *.xyz
How can i get all files on disk with a specific extension using 'Directory.getFiles' and save them in a list
There are two things you can do to improve that code:
- Use
Directory.EnumerateFiles()
andDirectory.EnumerateDirectories()
to avoid making a copy of the names of all the files in each directory. - Make the return type of the method
IEnumerable<string>
to make it easier to consume.
We also need to be very careful about exceptions caused by attempting to access protected files and directories. The code below is also complicated by the fact that you're not allowed to yield return
from inside a try/catch
block, so we have to rearrange the code somewhat.
(Also note that we have to dispose the enumerator returned from .GetEnumerator()
; normally this is done automatically when you use foreach
, but in this case we can't - because of having to avoid doing yield return
in a try/catch
- so we have to use using
to dispose it.)
Here's a modification of your original code to do this:
public static IEnumerable<string> GetFiles(string root, string spec)
{
var pending = new Stack<string>(new []{root});
while (pending.Count > 0)
{
var path = pending.Pop();
IEnumerator<string> fileIterator = null;
try
{
fileIterator = Directory.EnumerateFiles(path, spec).GetEnumerator();
}
catch {}
if (fileIterator != null)
{
using (fileIterator)
{
while (true)
{
try
{
if (!fileIterator.MoveNext()) // Throws if file is not accessible.
break;
}
catch { break; }
yield return fileIterator.Current;
}
}
}
IEnumerator<string> dirIterator = null;
try
{
dirIterator = Directory.EnumerateDirectories(path).GetEnumerator();
}
catch {}
if (dirIterator != null)
{
using (dirIterator)
{
while (true)
{
try
{
if (!dirIterator.MoveNext()) // Throws if directory is not accessible.
break;
}
catch { break; }
pending.Push(dirIterator.Current);
}
}
}
}
}
As an example, here's how you could use a console app to list all the accessible ".txt" files on the "C:\" drive:
static void Main()
{
foreach (var file in GetFiles("C:\\", "*.txt"))
{
Console.WriteLine(file);
}
}
Related Topics
Passing a Variable as a Template Argument
Order of Evaluation of Elements in List-Initialization
How to Find the Actual Path Found by Bfs
Random Array Generation with No Duplicates
"The System Cannot Find the File Specified" When Running C++ Program
How to Use Polymorphic Attributes with Boost::Spirit::Qi Parsers
C++17 Class Template Partial Deduction
Create a Function to Check for Key Press in Unix Using Ncurses
How to Declare a Member Vector of the Same Class
No Match for 'Operator<<' in 'Std::Operator
Good Tools for Creating a C/C++ Parser/Analyzer
Temporary Objects - When Are They Created, How to Recognise Them in Code
Choosing Between Std::Map and Std::Unordered_Map
What Is the Meaning of "Operator Bool() Const"