Check whether a certain file type/extension exists in directory
#!/bin/bash
count=`ls -1 *.flac 2>/dev/null | wc -l`
if [ $count != 0 ]
then
echo true
fi
Check if a directory contains a file with a given extension
You can use the else
block of the for
:
for fname in os.listdir('.'):
if fname.endswith('.true'):
# do stuff on the file
break
else:
# do stuff if a file .true doesn't exist.
The else
attached to a for
will be run whenever the break
inside the loop is not executed. If you think a for
loop as a way to search something, then break
tells whether you have found that something. The else
is run when you didn't found what you were searching for.
Alternatively:
if not any(fname.endswith('.true') for fname in os.listdir('.')):
# do stuff if a file .true doesn't exist
Moreover you could use the glob
module instead of listdir
:
import glob
# stuff
if not glob.glob('*.true')`:
# do stuff if no file ending in .true exists
How can I check if a certain file type exists in a directory?
You could do something like
Dir['some_dir/*.exe'].any?
With subfolders
Dir['some_dir/**/*.exe'].any?
check if file with certain file extension present in folder using batch script
In the simplest case the batch language includes a construct for this task
if exist *.elf (
:: file exists - do something
) else (
:: file does not exist - do something else
)
where the if exist
will test for existence of an element in the current or indicate folder that matches the indicated name/wildcard expression.
While in this case it seems you will not need anything else, you should take into consideration that if exist
makes no difference between a file and a folder. If the name/wildcard expression that you are using matches a folder name, if exists
will evaluate to true.
How to ensure we are testing for a file? The easiest solution is to use the dir
command to search for files (excluding folders). If it fails (raises errorlevel), there are no files matching the condition.
dir /a-d *.elf >nul 2>&1
if errorlevel 1 (
:: file does not exist - do something
) else (
:: file exists - do something else
)
Or, using conditional execution (just a little abreviation for the above code)
dir /a-d *.elf >nul 2>&1 && (
:: file does exist - do something
) || (
:: file does not exist - do something else
)
What it does is execute a dir
command searching for *.elf
, excluding folders (/a-d
) and sending all the output to nul
device, that is, discarding the output. If errorlevel is raised, no matching file has been found.
How to check if a directory contains a certain file type?
If you just want to check the count of .txt
files is 0
then you could use glob.glob()
instead:
import glob
if len(glob.glob("*.txt")) == 0:
print "No TXT files"
Checking if file with file-extension '.ini' exists, shell
set -- /dir/*.ini
case $1 in
('/dir/*.ini') echo "No ini files here.";;
(*) echo "Found $# ini files: $@";;
esac
Look ma! No forks! This should beat, by a million of CPU cycles, any solution with forks to ls
, find
and friends.
Now there's one little gotcha here. Can you spot it? Okay, what happens if /dir
contains a file named *.ini
literally (star, dot, ini)? The above will give you a false negative: it reports no ini file although there is one. If you want to prepare for this case (and you should, because you are a careful programmer, giving attention to detail, no gotchas in your code, right?), you slightly modify the first case to read
('/dir/*.ini')
if test -f '/dir/*.ini'; then
echo "Wow, there's a plain file named '/dir/*.ini'!"
else
echo "No ini files here."
fi;;
how to check if a specific file extension exists in a folder using powershell?
Try this:
function Get-ExtensionCount {
param(
$Root = "C:\Root\",
$FileType = @(".sln", ".designer.vb"),
$Outfile = "C:\Root\rootext.txt"
)
$output = @()
Foreach ($type in $FileType) {
$files = Get-ChildItem $Root -Filter *$type -Recurse | ? { !$_.PSIsContainer }
$output += "$type ---> $($files.Count) files"
foreach ($file in $files) {
$output += $file.FullName
}
}
$output | Set-Content $Outfile
}
I turned it into a function with your values as default parameter-values. Call it by using
Get-ExtensionCount #for default values
Or
Get-ExtensionCount -Root "d:\test" -FileType ".txt", ".bmp" -Outfile "D:\output.txt"
Output saved to the file ex:
.txt ---> 3 files
D:\Test\as.txt
D:\Test\ddddd.txt
D:\Test\sss.txt
.bmp ---> 2 files
D:\Test\dsadsa.bmp
D:\Test\New Bitmap Image.bmp
To get the all the filecounts at the start, try:
function Get-ExtensionCount {
param(
$Root = "C:\Root\",
$FileType = @(".sln", ".designer.vb"),
$Outfile = "C:\Root\rootext.txt"
)
#Filecount per type
$header = @()
#All the filepaths
$filelist = @()
Foreach ($type in $FileType) {
$files = Get-ChildItem $Root -Filter *$type -Recurse | ? { !$_.PSIsContainer }
$header += "$type ---> $($files.Count) files"
foreach ($file in $files) {
$filelist += $file.FullName
}
}
#Collect to single output
$output = @($header, $filelist)
$output | Set-Content $Outfile
}
Is there an R function for checking if files with a certain extension exist in a path?
Using base R:
list.files(path = "pathname", pattern = "\\.csv$")
will return a vector of strings with the filenames that end in ".csv". To check if any exist, use:
length(list.files(path = "pathname", pattern = "\\.csv$")) > 0
How can I Check whether file exists with a specific extension in a folder
The below code may help you.
public class FindCertainExtension {
private static final String FILE_DIR = "c:\\folder";
private static final String FILE_TEXT_EXT = ".jpg";
public static void main(String args[]) {
new FindCertainExtension().listFile(FILE_DIR, FILE_TEXT_EXT);
}
public void listFile(String folder, String ext) {
GenericExtFilter filter = new GenericExtFilter(ext);
File dir = new File(folder);
if(dir.isDirectory()==false){
System.out.println("Directory does not exists : " + FILE_DIR);
return;
}
// list out all the file name and filter by the extension
String[] list = dir.list(filter);
if (list.length == 0) {
System.out.println("no files end with : " + ext);
return;
}
for (String file : list) {
String temp = new StringBuffer(FILE_DIR).append(File.separator)
.append(file).toString();
System.out.println("file : " + temp);
}
}
// inner class, generic extension filter
public class GenericExtFilter implements FilenameFilter {
private String ext;
public GenericExtFilter(String ext) {
this.ext = ext;
}
public boolean accept(File dir, String name) {
return (name.endsWith(ext));
}
}
}
Enjoy !!!
Related Topics
Gpg: Sorry, No Terminal at All Requested - Can't Get Input
Are There Any Good Postgresql Clients for Linux
Linux: Getting Umask of an Already Running Process
How to Find Which Yocto Project Recipe Populates a Particular File on an Image Root Filesystem
Awk - Count Each Unique Value and Match Values Between Two Files
Executing String Sent from One Terminal in Another in Linux Pseudo-Terminal
How to Correctly Cleanup and Re-Use Sysv Shared Memory Segments
How to Use "Py" Instead of "Python" at the Command Line in Linux
How to Shell Have More Than One Job in Linux
How to Determine the Current Ip from a Known MAC Address
Fata[0000] Get Http:///Var/Run/Docker.Sock/V1.17/Version: Dial Unix /Var/Run/Docker.Sock
Surround All Lines in a Text File with Quotes ('Something')
Error When Trying to Run .Asm File on Nasm on Ubuntu
Convert Multipage PDF to a Single Image
In Linux Determine If a .A Library/Archive 32-Bit or 64-Bit
How to Find a File/Directory That Could Be Anywhere on Linux Command Line