如何使用for循环遍历目录中的每个文件?
我如何判断某个条目是一个目录还是一个文件?
如何使用for循环遍历目录中的每个文件?
我如何判断某个条目是一个目录还是一个文件?
当前回答
下面的代码在当前目录中创建一个名为“AllFilesInCurrentDirectorylist.txt”的文件,其中包含当前目录中所有文件(仅为文件)的列表。看看吧
dir /b /a-d > AllFilesInCurrentDirectorylist.txt
其他回答
它也可以使用forfiles命令:
forfiles /s
还要检查它是否是一个目录
forfiles /p c:\ /s /m *.* /c "cmd /c if @isdir==true echo @file is a directory"
我很难让jop的答案与绝对路径一起工作,直到我发现这个参考:https://ss64.com/nt/for_r.html
下面的示例循环遍历一个由绝对路径给出的目录中的所有文件。
For /R C:\absoulte\path\ %%G IN (*.*) do (
Echo %%G
)
在我的情况下,我必须删除临时文件夹下的所有文件和文件夹。这就是我最后做这件事的原因。我必须运行两个循环一个文件和一个文件夹。如果文件或文件夹名称中有空格,则必须使用" "
cd %USERPROFILE%\AppData\Local\Temp\
rem files only
for /r %%a in (*) do (
echo deleting file "%%a" ...
if exist "%%a" del /s /q "%%a"
)
rem folders only
for /D %%a in (*) do (
echo deleting folder "%%a" ...
if exist "%%a" rmdir /s /q "%%a"
)
我会使用vbscript (Windows脚本主机),因为在批处理中,我确信你不能区分一个名称是一个文件还是一个目录。
在vbs中,它可以是这样的:
Dim fileSystemObject
Set fileSystemObject = CreateObject("Scripting.FileSystemObject")
Dim mainFolder
Set mainFolder = fileSystemObject.GetFolder(myFolder)
Dim files
Set files = mainFolder.Files
For Each file in files
...
Next
Dim subFolders
Set subFolders = mainFolder.SubFolders
For Each folder in subFolders
...
Next
检查MSDN上的FileSystemObject。
遍历您可以使用的所有文件和文件夹
for /F "delims=" %%a in ('dir /b /s') do echo %%a
若要只遍历所有文件夹而不遍历文件,则可以使用
for /F "delims=" %%a in ('dir /a:d /b /s') do echo %%a
其中/s将以无限深度给出整个目录树的所有结果。如果您想遍历该文件夹的内容而不是其子文件夹的内容,则可以跳过/s
在迭代中实现搜索
要遍历特定的命名文件和文件夹,您可以搜索名称并使用for循环进行迭代
for /F "delims=" %%a in ('dir "file or folder name" /b /s') do echo %%a
要遍历特定的命名文件夹/目录而不是文件,请在同一命令中使用/AD
for /F "delims=" %%a in ('dir "folder name" /b /AD /s') do echo %%a