Search code examples
macosapplescriptphoto

Using AppleScript to export individual photo titles to text file from MacOS Photos App


I would like to scan thru my Photo library (macOS 10.15.6, Photos App 5.0) and export selected photos' original file name to a text file. I have a simple script below as a starting point that doesn't properly convert the filename to readable text. I expect I need to execute some kind of 'convert to string' operation on the filename but I'm coming up empty on answers...

Any suggestions would be appreciated

code I'm currently using:

set myFile to open for access "/Users/ed/Desktop/testFile.txt" with write permission
write "file start\n" to myFile

tell application "Photos"
    activate
    set imageSel to (get selection)
    if imageSel is {} then
        error "Please select an image."
    else
        repeat with im in imageSel
            write filename of im to myFile
            write "\nnext photo\n" to myFile
        end repeat
        
    end if
end tell

write "file end\n" to myFile
close access myFile

Solution

  • My suggestion is to build the list of file names, then convert the list to paragraphs with text item delimiters and write the text to disk.

    Further it's highly recommended to add reliable error handling to the write part.

    tell application "Photos"
        set imageSel to selection
        if imageSel is {} then
            error "Please select an image."
        else
            set theNames to {"file start"}
            repeat with im in imageSel
                set end of theNames to filename of im
            end repeat
            set end of theNames to "file end"
        end if
    end tell
    set {TID, text item delimiters} to {text item delimiters, linefeed}
    set theNames to theNames as text
    set text item delimiters to TID
    
    set testFile to POSIX path of (path to desktop) & "testFile.txt"
    try
        set fileDescriptor to open for access testFile with write permission
        write theNames to fileDescriptor
        close access fileDescriptor
    on error
        try
           close testFile
        end try
    end try