I have a file, say, "123.xyz", opened in TextWrangler.
How can I use Applescript to get the "its absolute path + full name" of the currently opened file.
So that I could use this in another program or script.
I modified some code I found online, but it didn't work for me.
tell application "TextWrangler"
tell document 1
-- Get (absolute path + filename) of the current file
set FileName to «class ppth» as text
end tell
end tell
Any help is highly appreciated.
tell application "TextWrangler"
--This will return the file path of document 1 in the following format: file "Macintosh HD:Users:UserName:Desktop:document1.txt"
set filePath1 to file of document 1
--This will convert the file path of document 1 to the following format: "Users/UserName/Desktop/document1.txt"
set filePath2 to POSIX path of filePath1
end tell
This SHOULD work:
tell document 1 to set myVeryOwnPath to path as text
Related
I was looking for a script that would batch convert all *.numbers files in a given folder to *.csv files.
I found the following on GitHub and added an additional line as suggested in the comments suggestion. When I run the script, Numbers launches and opens the test file from the folder specified - but the file is not exported. Numbers just stays open and terminal errors out with:
/Users/Shared/Untitled.scpt: execution error: Numbers got an error: Invalid key form. (-10002)
The script (located in /Users/Shared) has the following permissions:
-rwxr-xr-x
#!/usr/bin/osascript
on run argv
set theFilePath to POSIX file (item 1 of argv)
set theFolder to theFilePath as alias
tell application "Finder" to set theDocs to theFolder's items
-- Avoid export privilege problem
set privilegeFile to (theFolder as text) & ".permission"
close access (open for access privilegeFile)
repeat with aDoc in theDocs
set docName to aDoc's name as text
if docName ends with ".numbers" then
set exportName to (theFolder as text) & docName
set exportName to exportName's text 1 thru -9
set exportName to (exportName & "csv")
tell application "Numbers"
open aDoc
delay 5 -- may need to adjust this higher
tell front document
export to file exportName as CSV
close
end tell
end tell
end if
end repeat
end run
Any suggestions?
Here is what I did and works for me in macOS High Sierra:
In Terminal:
touch numb2csv; open -e numb2csv; chmod +x numb2csv
• This creates an empty ASCII Text file named numb2csv.
• Opens, by default, numb2csv in TextEdit.
• Makes the numb2csv file executable.
Copy and paste the example AppleScript code, shown further below, into the opened numb2csv file.
Save and close the numb2csv file.
In Terminal executed the numb2csv executable file, e.g.:
./numb2csv "$HOME/Documents"
This created a CSV file of the same name as each Numbers document in my Documents folder, not traversing any nested folders.
Example AppleScript code:
#!/usr/bin/osascript
on run argv
set theFilePath to POSIX file (item 1 of argv)
set theFolder to theFilePath as alias
tell application "System Events" to set theDocs to theFolder's items whose name extension = "numbers"
repeat with aDoc in theDocs
set docName to aDoc's name as text
set exportName to (theFolder as text) & docName
set exportName to exportName's text 1 thru -8
set exportName to (exportName & "csv")
tell application "Numbers"
launch
open aDoc
repeat until exists document 1
delay 3
end repeat
tell front document
export to file exportName as CSV
close
end tell
end tell
end repeat
tell application "Numbers" to quit
end run
NOTE: As coded, this will overwrite an existing CSV file of the same name as each Numbers file processed, if they already exist. Additional coding required if wanting to not overwrite existing files
If you receive the Script Error:
Numbers got an error: The document “name” could not be exported as “name”. You don’t have permission.
It is my experience that the Numbers document was not fully opened prior to being exported and that increasing the value of the delay command resolves this issue. This is of course assuming that one actually has write permissions in the folder the target Numbers documents exists.
Or one can introduce an error handler within the tell front document block which, if my theory is right about the target document not being fully loaded before the export, will give additional time, e.g.:
Change:
tell front document
export to file exportName as CSV
close
end tell
To:
tell front document
try
export to file exportName as CSV
close
on error
delay 3
export to file exportName as CSV
close
end try
end tell
Note: The primary example AppleScript code is just that and does not contain any error handling as may be appropriate. The onus is upon the user to add any error handling as may be appropriate, needed or wanted. Have a look at the try statement and error statement in the AppleScript Language Guide. See also, Working with Errors. See included example directly above.
I was looking for that, unfortunately, that doesn’t work anymore.
This line
tell application "System Events" to set theDocs to theFolder's items whose name extension = "numbers"
Gets the following error:
execution error: Can’t make file "file.numbers" of application "System Events" into the expected type. (-1700)
macOs Big Sur Versio 11.01
automator version 2.10
Numbers version 10.3.5
Inspired by this thread and those articles Exporting Numbers Documents and Get full directory contents with AppleScript
The following code works:
#!/usr/bin/osascript
log "Start"
property exportFileExtension : "csv"
tell application "Finder"
activate
set sourceFolder to choose folder with prompt "Please select directory."
set fileList to name of every file of sourceFolder
end tell
set the defaultDestinationFolder to sourceFolder
repeat with documentName in fileList
log "documentName: " & documentName
set fullPath to (sourceFolder as text) & documentName
log "fullPath: " & fullPath
if documentName ends with ".numbers" then
set documentName to text 1 thru -9 of documentName
tell application "Finder"
set newExportItemName to documentName & "." & exportFileExtension
set incrementIndex to 1
repeat until not (exists document file newExportItemName of defaultDestinationFolder)
set newExportItemName to ¬
documentName & "-" & (incrementIndex as string) & "." & exportFileExtension
set incrementIndex to incrementIndex + 1
end repeat
end tell
set the targetFileHFSPath to ¬
(defaultDestinationFolder as string) & newExportItemName
tell application "Numbers"
launch
open fullPath
with timeout of 1200 seconds
export front document to file targetFileHFSPath as CSV
end timeout
close
end tell
end if
end repeat
user3439894's answer works with a few change:
exists document 1 => number of documents > 0
Firstly, let me stress that I have almost no Applescript experience. I'm an Oracle developer by trade, so please assume my knowledge is ZERO so I'd be grateful if you could really dumb down your response.
I wrote this script a year or so ago and it has suddenly stopped working. I'm guessing that a macOS upgrade (on High Sierra) no longer tolerates my probably poorly written script.
on run {input, parameters}
repeat with theFile in input
set FileName to theFile as text
tell application "Finder"
if FileName ends with "-xs.jpg" then
--label value, 0 is no label, 1 Orange, 2 Red, 6 Geen
set the label index of file FileName to 6
move FileName to folder "Macintosh HD:Users:Karla:Pictures:FTP:basket-[xs]:" with replacing
else if FileName ends with "-sm.jpg" then
set the label index of file FileName to 1
move FileName to folder "Macintosh HD:Users:Karla:Pictures:FTP:thumbnails-[sm]:" with replacing
else if FileName ends with "-lg.jpg" then
set the label index of file FileName to 2
move FileName to folder "Macintosh HD:Users:Karla:Pictures:FTP:main-[lg]:" with replacing
else if FileName ends with "-xlg.jpg" then
set the label index of file FileName to 5
move FileName to folder "Macintosh HD:Users:Karla:Pictures:FTP:large-[xlg]:" with replacing
end if
end tell
end repeat
return input
end run
The error I get is "The action "Run AppleScript" encountered an error: "Finder got an error: Can't set file "Macintosh HD:Users:Karla:Pictures:1-IMAGES-TO-DO:image1-lg.jpg" to 2."
If I comment out the tagging and try to just do the move, I get "The action "Run AppleScript" encountered an error: "Finder got an error: Can't get folder "Mackintosh HD:Users:Karla:Pictures:FTP:main-[lg]:"."
Edit:
I have also tried:
on run {input, parameters}
repeat with the_input_file in input
set FileName to POSIX file (the_input_file as alias)
end repeat
return input
end run
but get the error The action "Run AppleScript" encountered the error: "Can't get POSIX file (alias "Macintosh HD:Users:Karla:Pictures:file.jpg")."
Edit again:
So this is where I am. I've created a droplet as follows:
on open theDroppedItems
set lg_folder to POSIX path of "Macintosh HD:Users:Karla:Pictures:test1:"
repeat with current_item_cnt from 1 to count of theDroppedItems
-- load the next file in the_file
set the_current_file to item current_item_cnt of theDroppedItems
move file the_current_file to lg_folder
end repeat
end open
And I still get a -1728 error onthe file. "Can’t get file (alias \"Macintosh HD:Users:Karla:Pictures:test1:test-lg.jpg\")." number -1728 from file (alias "Macintosh HD:Users:Karla:Pictures:test1:test-lg.jpg")
I've spent 2 days on a script that used to work and now inexplicably does not in amongst trying to do my real job. This is supposed to make my life easier.
Try using this code for your droplet...
property folderXS : "Macintosh HD:Users:Karla:Pictures:FTP:basket-[xs]"
property folderSM : "Macintosh HD:Users:Karla:Pictures:FTP:thumbnails-[sm]"
property folderLG : "Macintosh HD:Users:Karla:Pictures:FTP:main-[lg]"
property folderXL : "Macintosh HD:Users:Karla:Pictures:FTP:large-[xlg]"
on run
-- Executed when the script is launched
set theFiles to choose file with prompt ¬
"Choose Files" multiple selections allowed true ¬
without showing package contents
repeat with theFile in theFiles
set FileName to theFile as text
tell application "Finder"
if FileName ends with "-xs.jpg" then
--label value, 0 is no label, 1 Orange, 2 Red, 6 Green
set the label index of file FileName to 6
move FileName to folder folderXS with replacing
else if FileName ends with "-sm.jpg" then
set the label index of file FileName to 1
move FileName to folder folderSM with replacing
else if FileName ends with "-lg.jpg" then
set the label index of file FileName to 2
move FileName to folder folderLG with replacing
else if FileName ends with "-xlg.jpg" then
set the label index of file FileName to 5
move FileName to folder folderXL with replacing
end if
end tell
end repeat
return theFiles
end run
on open theDroppedItems
-- Executed when files are dropped on the script
set lg_folder to "Macintosh HD:Users:Karla:Pictures:test1"
repeat with current_item_cnt from 1 to count of theDroppedItems
set the_current_file to item current_item_cnt of theDroppedItems
tell application "Finder"
move file the_current_file to lg_folder
end tell
end repeat
end open
If anybody comes here as I did, looking for an answer, I can give you an inelegant, hacky way to at least get this working. I had variable this_item which contained an HFS file which I wanted to move into todaysFolder.
Part of the problem is Finder doesn't always know what to do with POSIX paths involving variables, and sometimes you need to use the "my" keyword first. Other time, you need to leave it out. I couldn't figure out the logic.
The following ridiculous code block does it reliably and seems to catch every strange, inscrutable exception.
try
move my (POSIX file (POSIX path of this_item)) to folder (todaysFolder) of disk "Hard Drive" with replacing
on error
try
move (POSIX file (POSIX path of this_item)) to folder (todaysFolder) of disk "Hard Drive" with replacing
on error
try
move (file (POSIX path of this_item)) to folder (todaysFolder) of disk "Hard Drive" with replacing
on error
move (file (this_item)) to folder (todaysFolder) of disk "Hard Drive" with replacing
end try
end try
end try
What I'm trying to make is something like this:
set filename to (choose file)
display dialog "The name of the chosen file is: " & filename
But when I use that script it will return a path to the file something like .../.../.../.../nameoffile.jar. But what I want is that it will return the filename and not the path (so just only nameoffile.jar). Is there a way to do that?
Thanks for reading, please give an answer as soon as possible ;),
Jort
Use the Finder Suite:
set chosenfile to (choose file)
tell application "Finder"
display dialog "The name of the chosen file is: " & (name of chosenfile)
end tell
(This is a new edit from a previous question of mine which achieved -3 votes. Hope this new one has a better qualification)
I need to create an Automator service to organize a high amount of files into folders. I work with illustrator and from each .ai file I create 3 more formats: [name.pdf], [name BAJA.jpg] and [name.jpg], thats 4 files in total
My problem is that during the week I repeat this process to more than 90 different .ai files. So 90 files * 4 is 360 independent files all into the some project folder.
I want to grab all 4 related files into one folder, and set the folder name as the same as the .ai file.
Since all the file names are identical (except one), I thought of telling the finder to grab all the files with the same name, copy the name, create a folder and put this files inside, but I have a file name variant [name LOW.jpg] Maybe I can tell the script to strip that work as an exception.
That way I will all 4 the files unified into one folder.
Thank you in advance
Update: This problem was originally posted back in 2013, now I have a solution. People help me assembled this script to fit my needs.
I added this as a service and assigned a keyboard shurtcut on MacOs.
This is the code:
on run {input, parameters} -- create folders from file names and move
set output to {} -- this will be a list of the moved files
repeat with anItem in the input -- step through each item in the input
set {theContainer, theName, theExtension} to (getTheNames from anItem)
try
# check for a suffix and strip it off for the folder name
if theName ends with " BAJA" then
set destination to (makeNewFolder for (text 1 thru -6 of theName) at theContainer)
else
set destination to (makeNewFolder for theName at theContainer)
end if
tell application "Finder"
move anItem to destination
set the end of the output to the result as alias -- success
end tell
on error errorMessage -- duplicate name, permissions, etc
log errorMessage
# handle errors if desired - just skip for now
end try
end repeat
return the output -- pass on the results to following actions
end run
to getTheNames from someItem -- get a container, name, and extension from a file item
tell application "System Events" to tell disk item (someItem as text)
set theContainer to the path of the container
set {theName, theExtension} to {name, name extension}
end tell
if theExtension is not "" then
set theName to text 1 thru -((count theExtension) + 2) of theName -- just the name part
set theExtension to "." & theExtension
end if
return {theContainer, theName, theExtension}
end getTheNames
to makeNewFolder for theChild at theParent -- make a new child folder at the parent location if it doesn't already exist
set theParent to theParent as text
if theParent begins with "/" then set theParent to theParent as POSIX file as text
try
return (theParent & theChild) as alias
on error errorMessage -- no folder
log errorMessage
tell application "Finder" to make new folder at theParent with properties {name:theChild}
return the result as alias
end try
end makeNewFolder
Hope this helps.
It's a pity you get downvoted as I, personally, enjoy answering these sorts of questions, as it helps me practise and improve my own skills.
Thanks for posting your solution. I think it's a great gesture and others will find it useful.
This script is a bit shorter than and uses "System Events" instead of "Finder", so will be quicker for large numbers of files:
set IllustratorOutputFolder to "/Users/CK/Desktop/example"
tell application "System Events" to ¬
set ai_files to every file in folder IllustratorOutputFolder ¬
whose name extension is "ai"
set Output to {}
repeat with ai_file in ai_files
set AppleScript's text item delimiters to "."
get name of ai_file
get text items of result
set basename to reverse of rest of reverse of result as text
tell application "System Events"
get (every file in folder IllustratorOutputFolder ¬
whose name begins with basename)
move result to (make new folder ¬
in folder IllustratorOutputFolder ¬
with properties {name:basename})
end tell
set end of Output to result
end repeat
return Output -- list of lists of moved files
Just an alternative way of doing things. Not that it's better or worse, but just a different solution.
You could also save this as script.sh (in TextEdit in plain text mode) and run it with bash script.sh in Terminal:
cd ~/Target\ Folder/
for f in *.ai *.pdf *.jpg; do
dir=${f%.*}
dir=${dir% LOW}
mkdir -p "$dir"
mv "$f" "$dir"
done
This is my first applescript. I thought I'd do something simple like navigating to a folder using a path and listing the subfolders...Unfortunately, I can't figure it out :-)
Here is what I've tried so far:
The first try:
tell application "Finder"
set the_folder to POSIX path of "Users:MyName:Doc"
log the_folder
set folder_list to every item of folder the_folder
log folder_list
end tell
This produces an error:
"Finder got an error: Can't get folder "/Users/MyName/Doc".
Could someone please:
1. Explain to me what I'm doing wrong.
2. Provide an example that works.
Thanks in advance.
btw the folder does exist on my machine...
UPDATE: Oops! It appears that I have given you the wrong information so I will give you the correct information.
The command POSIX path of requires a complete alias reference. By that I mean supplying the full file reference (i.e. <your_disk_name>:Users:<your_user_name>:somefolder:). Make sure that if you're referring to a folder that you end the reference with a colon (i.e. Macintosh HD:Users:). An improved version would look like this:
tell application "Finder"
set the_folder to (POSIX path of ("<your_disk_name>:Users:<your_user_name>:Doc:") as alias) as alias
set folder_list to every item of the_folder
end tell
OPTIONAL
To coerce a POSIX path (i.e. /Users/<your_user_name>/somefolder) back into an alias, two conversions are needed.
Conversion 1: The first step is to convert the reference into a file reference. To do this, place the words as POSIX file after the reference, like so:
"/Users/<your_user_name>/somefolder" as POSIX file
This code procudes a file reference in this form: file "<your_disk_name>:Users:<your_user_name>:somefolder:"
Conversion 2: Add a second coercion, as alias, to the end of the reference...
"/Users/<your_user_name>/somefolder" as POSIX file as alias
This code produces an actual alias reference: alias "<your_disk_name>:Users:<your_user_name>:somefolder:
If you have any questions, just ask. :)
Posix paths are paths you use at the command line and are "/" delimited. Applescript paths are ":" separated so just use those. Try this script to see what the path should look like...
set folderPath to (choose folder) as text