Get folder and file names and store it in a variable in windows?
Solution 1
FOR %%f in (folder1\*) DO @echo %%f
in a batch file will echo the filename of each file in the folder. To do the same thing at the command line, use only one percent sign for the variable. You can replace echo
with some other command.
If you quote the %%f
, the echo
will output the quotes around the filename, but if you want to pass the filename to other commands the quotes may be necessary if there are special characters, such as spaces, in the filenames. For example, to output the contents of all the files:
FOR %%f in (folder1\*) DO @type "%%f"
Without the quotes, if there was a file named "Has Space", type
would try to output the contents of two files, "Has" and "Space". With the quotes, it will work as intended.
Solution 2
If you want to upgrade from batch to powershell:
Foreach ($file in Get-Childitem "<PATH>") {
$file.name
}
$filenames = (Get-ChildItem -Path "PATH" -Directory).Name
Solution 3
Assuming this is in a batch file, you could do it in a for loop like this:
setlocal EnableDelayedExpansion
for %%a in (folder1\*) do (
set fileVariable=%%a
echo !fileVariable!
)
Related videos on Youtube
Cobra
Updated on September 17, 2022Comments
-
Cobra over 1 year
I want to find a file from current directory the executable is running, say -
delta001.png
if it does not exists then print it.
If it exists then print -
delta002.png
The name of the file to be printed is 'delta' but the number would be the next number which is found in the directory. The number could be anything like - '112', 334, 234, 087 etc. Python 3 or higher.
Thanks in advance.
-
kylieCatt over 10 yearsThis is probably what you are looking for docs.python.org/2/library/glob.html
-
-
Joey over 13 yearsOr simply
gci <path> | select Name
. -
Ryflex over 10 yearsHe also needs to use something like
os.path.exists("delta.png")
to check if the file exists or not -
kylieCatt over 10 yearsWill glob find things that aren't there?
-
Ryflex over 10 yearsThanks @p99will, didn't spot that when I wrote it.
-
p99will over 10 years:D, Thanks. Only problem is knowing if this works for Python 3
Python 3 or higher.
As it think OP wants. I don't know anything about Py3. -
Cobra over 10 yearsSeems like it works, but in my case looping 999 times is not a good idea. It makes the application unresponsive. Thanks.
-
Cobra over 10 yearsOk, this seems to be working fine. I can't up vote, sorry, my rep is low and just lost one :). Thanks.
-
Sandra K over 6 yearsThis works even if file name has spaces in it?
-
Dennis Williamson over 6 years@SandraK: For many uses you should quote the
%%f
at the end. I've added some additional information to my answer.