Read filenames in a directory with AutoHotkey

2019-07-10 13:11发布

问题:

I am looking for a way to read a folder and save each filename to a variable. So far this is what I have

Loop,C:\My Documents\Notes\*

In my notes directory I have pdf files. I want to read the directory and save the filename "Homework1.pdf" to a variable then move the file itself to another directory. On the next loop it will pick up the next pdf document "Test.pdf" etc. This should loop until every pdf has been moved.

I know I could use FileMove but the samples show that you have to provide the specific filename to move. How can I adjust this to move each pdf file one by one?

回答1:

You can bypass creating a list to parse (assuming you don't need the variables for anything else) and use the built-in variables A_LoopFileFullPath and A_LoopFileName to accomplish this.

Loop, C:\My Documents\Notes\*.pdf
    FileCopy, % A_LoopFileFullPath, C:\NewPath\%A_LoopFileName%

EDIT: Try this for a preview of your result

Loop, C:\My Documents\Notes\*.pdf
    Msgbox % A_LoopFileFullPath "`nC:\NewPath\" A_LoopFileName


回答2:

FileList =
Loop, C:\My Documents\Notes\*
   FileList = %FileList%%A_LoopFileName%`n
Loop, parse, FileList, `n
   FileMove, %A_LoopField%, C:\NewLocation

Original source: http://www.autohotkey.com/docs/commands/LoopFile.htm