Bryan Dunphy Bryan Dunphy - 4 years ago 141
AppleScript Question

In Applescript, Why does my "Tell app Finder" block not delete "f" even when it exists?

This question is similar to AppleScript set directory path in Finder but the answer there did not work for me!

local destination, libraryName, f
set destination to "/Users/bryandunphy/Music/Result"
set libraryName to "Testing"
if not ((libraryName ends with ".xml") or (libraryName ends with ".XML")) then set libraryName to libraryName & ".xml"
menuClick({"iTunes", "File", "Library", "Export Library…"})
set f to "/Users/bryandunphy/Music/Result/Testing.xml" -- (destination & "/" & libraryName) as string
tell application "Finder"
if POSIX file f exists then
delete f
end if
end tell
tell application "System Events" to tell process "iTunes" to tell its front window to set the value of its text field "Save As:" to libraryName
if switchDir(destination, "iTunes", true, true) then return destination & "/" & libraryName -- first true = click default (Save) button, last = create path if needed

The "if switchDir" line causes a "File Exists, Replace?" dialog to appear.

Answer Source

The simplest solution is to use alias objects in the "System Events" context:

set f to "/Users/bryandunphy/Music/Result/Testing.xml" # sample POSIX path
tell alias f of application "System Events"
    if it exists then delete it
end tell

Caveat: This instantly deletes the target file instead of moving it to the trash folder.
To do the latter, see the Finder-based solution below.

In the "System Events" context, alias objects can work directly with POSIX paths, and file operations can be performed as well.

Working in the "System Events" context rather than the "Finder" context is generally preferable for performance reasons, but note that not some operations are only possible in the "Finder" context - moving a file to the trash instead of instantly deleting it being one example.

As for why your "Finder"-context approach didn't work:

The ways of the AppleScript are mysterious: POSIX file f exists does not work - it doesn't detect the file's existence - but f as POSIX file exists does:

set f to "/Users/bryandunphy/Music/Result/Testing.xml" # sample POSIX path
tell application "Finder"
    if f as POSIX file exists then delete f as POSIX file
end tell

Another quirk: a tell f as POSIX file ... end tell block with if it exists then delete it in it - analogous to the "System Events" solution above - does not work.

Unlike the "System Events" solution at the top, this:

  • moves the file to the trash instead of deleting it right away,
    • which causes the system sound for moving something to the trash to sound.
  • returns the file object that was just moved to the trash (already in its new location, the trash folder).
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download