0

I'm trying to add new folders added to a drive onto a textEdit or numbers file so that there's an up to date list of what projects I have active on individual drives.

I'm very new to AppleScript so I don't know what my limitations are, but I basically just need to figure out how to append to the end of the file (it seems like textEdit would be simplest) with the name of the new folder. I currently have:

on adding folder items to theAttachedFolder after receiving theNewItems
-- Get the name of the attached folder
tell application "Finder"
    set theName to name of theAttachedFolder
    
    -- Count the new items
    set theCount to length of theNewItems
    
    -- Display an alert indicating that the new items were received
    activate
    display alert "Attention!" message (theCount & " new items were detected in folder. Adding to TextEdit file.")
        
    end repeat
end tell

Any help is much appreciated. Thank you!

1 Answers1

0

The File Read/Write suite in the StandardAdditions scripting dictionary has open for access and write commands that can be used to append to a text file (the AppleScript Language Guide also has a command reference), and AppleScript's text item delimiters or string concatenation can be used to assemble a string from the list of file items.

There are some older topics describing ways to write to a file, but in the following example I've separated the main stuff from the folder action handler so that it can also be called from the run handler for testing in the Script Editor:

property logFile : "/path/to/output/textfile.txt" -- HFS or POSIX

on run -- test
   set folderItems to (choose file with multiple selections allowed)
   tell application "Finder" to set theFolder to container of first item of folderItems
   doStuff(theFolder, folderItems)
end run

on adding folder items to theAttachedFolder after receiving theNewItems
   doStuff(theAttachedFolder, theNewItems)
end adding folder items to

to doStuff(theFolder, theItems)
   set folderItems to ""
   activate
   display alert "Attention!" message "" & (count theItems) & " new items were detected in folder." & return & "Adding to log file."
  tell application "Finder" to set folderName to name of theFolder
  repeat with anItem in theItems
      tell application "Finder" to set newName to name of anItem
      set folderItems to folderItems & tab & newName & return
   end repeat
   writeToFile(logFile, "Items added to " & folderName & ":" & return & folderItems & return)
end doStuff

to writeToFile(someFile, someText)
   try
      set theOpenFile to (open for access someFile with write permission)
      write someText to theOpenFile starting at eof -- append
      close access theOpenFile
   on error -- make sure file is closed
      try
         close access theOpenFile
      end try
   end try
end writeToFile
red_menace
  • 3,162
  • 2
  • 10
  • 18