Thursday, December 14, 2017

#1 2015-10-07 09:52:22 am

bmose
Member
From:: Massachusetts
Registered: 2006-01-03
Posts: 219

Getting the paths of Finder selection items efficiently

A common task is to get the paths to items currently selected in the Finder. The simplest approach, which converts each Finder reference to text in a repeat loop, can be noticeably slow for a large number of selected items:

Applescript:


-- Method #1:
set hfsPaths to {}
tell application "Finder"
   repeat with currItem in (get selection)
       set end of hfsPaths to currItem as text
   end repeat
end tell

A common way to improve efficiency is with the as alias list construct, which executes about 4 to 5 times faster.

Applescript:


-- Method #2:
set hfsPaths to {}
tell application "Finder"
   repeat with currItem in (get selection as alias list)
       set end of hfsPaths to currItem as text
   end repeat
end tell

A third approach entails bulk conversion of the selection to text and extraction of the paths using text item delimiters.  On my machine, Method #3 runs about 10 times faster than Method #1 and about 2.5 times faster than Method #2 and thus may be the preferred approach when processing a large number of items:

Applescript:


-- Method #3
set {tid, AppleScript's text item delimiters} to {AppleScript's text item delimiters, return}
tell application "Finder" to set hfsPaths to (selection as text)'s paragraphs
set AppleScript's text item delimiters to tid

The text item delimiter approach has been described by ccstone before (http://macscripter.net/viewtopic.php?pid=164036), but I thought it would be worthwhile pointing it out in a more widely viewed forum because of the frequency with which this task is performed.

Last edited by bmose (2015-10-07 10:11:22 am)


Filed under: Finder, selection, paths

Offline

 

Board footer

Powered by FluxBB

RSS (new topics) RSS (active topics)