views:

473

answers:

3

I Have a folder full of images and I need to create a text file of all the image names with applescript. Is there some way with Applescript to read in all the file names there are about 10k of them and then output this to a text file? Any help would be great! Thanks for reading.

+5  A: 

Why not just do it from terminal.

ls > pix.txt

OhioDude
+1  A: 

The following Applescript will write the names of files within a folder to a text file:

property theFolder : "File:Path:To:theFolder:"

tell application "Finder"

    -- Create text file on desktop to write filenames to
    make new file at desktop with properties {name:"theFile.txt"}
    set theFile to the result as alias
    set openFile to open for access theFile with write permission

    -- Read file names and write to text file
    set theFiles to every item of folder theFolder
    repeat with i in theFiles
     set fileName to name of i
     write fileName & "
" to openFile starting at eof
    end repeat

    close access openFile

end tell
tkenington
+1  A: 

You don't need to create a file before opening it for access. You can just do

set theFile to (theFolder & "thefile.txt")as string
set openFile to open for access theFile with write permission

Of course if the file exists it will overwrite it. You could use

set thefile to choose file name with prompt "name the output file"

'choose file name' returns a path without creating a file, and it asks the user if they want to overwrite if the file exists.

You can also use 'return' to put a line break in like so, it makes the code a bit neater:

write fileName & return to openFile


Of course if you want a simple and more elegant way of doing it, the command is where you need to be.

ls>thefile.txt

In this example the '>' writes the output from the ls (list directory) command to a file. You can run this from within an applescript

set thePosixDrectory to posix path of file thedirectory of app "Finder"
set theposixResults to posix path of file theresultfile of app "Finder"
do shell script ("ls \"" & thePosixDrectory & "\">\"" & theposixResults & "\"")as string

the posix path stuff is to turn applescript style directory:paths:to your:files into unix style /directory/paths/to\ your/files.

Note that the shell script that actually gets run will look like:

ls "/some/directory/path/">"/some/file/path.txt"

the quotes are there to stop spaces or other funky characters from confusing the shell script. To stop the quotes from being read as quotes in the applescript the backslash was used to "escape" them. You can also use single quotes, for more readable code thusly:

do shell script ("ls '" & thePosixDrectory & "'>'" & theposixResults & "'")as string

which will appear in the shell like

 ls '/some/directory/path/'>'/some/file/path.txt'

HTH

stib